From beb2f7c7fd20917f947e57c8194d479daabc5997 Mon Sep 17 00:00:00 2001 From: "kay.one" Date: Sat, 2 Mar 2013 10:25:39 -0800 Subject: [PATCH] removed sqlce --- NzbDrone.Common.Test/PathExtentionFixture.cs | 11 - NzbDrone.Common/PathExtentions.cs | 26 - NzbDrone.Core.Test/App.config | 10 - NzbDrone.Core.Test/CentralDispatchFixture.cs | 10 - .../Configuration/ConfigCachingFixture.cs | 2 +- NzbDrone.Core.Test/Framework/SqlCeTest.cs | 146 - NzbDrone.Core.Test/Framework/TestDbHelper.cs | 2 +- .../JobTests/EpisodeSearchJobTest.cs | 34 - .../JobTests/RenameSeasonJobFixture.cs | 17 +- .../MediaFileTests/CleanUpDatabaseFixture.cs | 132 - .../MediaFileTests/MediaFileServiceTest.cs | 13 +- NzbDrone.Core.Test/NzbDrone.Core.Test.csproj | 4 - .../ProcessDownloadFixture.cs | 1 - .../RecycleBinProviderTests/CleanupFixture.cs | 2 +- .../DeleteDirectoryFixture.cs | 2 +- .../DeleteFileFixture.cs | 2 +- .../RecycleBinProviderTests/EmptyFixture.cs | 2 +- .../ReferenceDataProviderTest.cs | 212 -- .../ProviderTests/SceneMappingProviderTest.cs | 92 +- .../SearchTests/GetSearchTitleFixture.cs | 7 +- .../ProviderTests/SearchTests/TestSearch.cs | 5 +- .../FindMatchingTvRageSeriesFixture.cs | 3 +- .../EpisodeProviderTest.cs | 86 +- ...deProviderTest_GetEpisodesByParseResult.cs | 10 +- .../GetEpisodeBySceneNumberFixture.cs | 5 +- .../TvTests/SeasonProviderTest.cs | 37 +- NzbDrone.Core/App.config | 10 - NzbDrone.Core/ContainerExtentions.cs | 12 - NzbDrone.Core/Datastore/BasicRepository.cs | 8 +- NzbDrone.Core/Datastore/ConnectionFactory.cs | 160 - NzbDrone.Core/Datastore/CustomeMapper.cs | 75 - NzbDrone.Core/Datastore/MigrationLogger.cs | 73 - .../Datastore/Migrations/Migration20110707.cs | 167 - .../Datastore/Migrations/Migration20110726.cs | 25 - .../Datastore/Migrations/Migration20110909.cs | 25 - .../Datastore/Migrations/Migration20111011.cs | 16 - .../Datastore/Migrations/Migration20111112.cs | 23 - .../Datastore/Migrations/Migration20111125.cs | 15 - .../Datastore/Migrations/Migration20120118.cs | 14 - .../Datastore/Migrations/Migration20120123.cs | 14 - .../Datastore/Migrations/Migration20120220.cs | 29 - .../Datastore/Migrations/Migration20120227.cs | 19 - .../Datastore/Migrations/Migration20120228.cs | 15 - .../Datastore/Migrations/Migration20120420.cs | 39 - .../Datastore/Migrations/Migration20120430.cs | 15 - .../Datastore/Migrations/Migration20120504.cs | 15 - .../Datastore/Migrations/Migration20120707.cs | 21 - .../Datastore/Migrations/Migration20120727.cs | 25 - .../Datastore/Migrations/Migration20120802.cs | 19 - .../Datastore/Migrations/Migration20120918.cs | 17 - .../Datastore/Migrations/Migration20120919.cs | 21 - .../Datastore/Migrations/Migration20121012.cs | 17 - .../Datastore/Migrations/Migration20121016.cs | 20 - .../Datastore/Migrations/Migration20121122.cs | 22 - .../Datastore/Migrations/Migration20121202.cs | 18 - .../Datastore/Migrations/Migration20121209.cs | 18 - .../Datastore/Migrations/Migration20121218.cs | 18 - .../Datastore/Migrations/Migration20121223.cs | 17 - .../Datastore/Migrations/Migration20121226.cs | 16 - .../Datastore/Migrations/Migration20130203.cs | 30 - .../Datastore/Migrations/NzbDroneMigration.cs | 51 - .../Datastore/Migrations/SchemaInfo.cs | 9 - NzbDrone.Core/Datastore/MigrationsHelper.cs | 54 - .../PetaPoco/EpisodeSeasonRelator.cs | 51 - NzbDrone.Core/Datastore/PetaPoco/PetaPoco.cs | 2708 ----------------- NzbDrone.Core/Datastore/SqlCeProxy.cs | 32 - .../ExternalNotificationDefinition.cs | 1 - NzbDrone.Core/Indexers/Indexer.cs | 2 +- NzbDrone.Core/Indexers/IndexerService.cs | 2 +- NzbDrone.Core/Indexers/NewznabDefinition.cs | 2 +- NzbDrone.Core/Indexers/NewznabService.cs | 2 +- NzbDrone.Core/Jobs/RefreshEpsiodeMetadata.cs | 14 +- NzbDrone.Core/Jobs/RenameSeasonJob.cs | 13 +- NzbDrone.Core/Jobs/RenameSeriesJob.cs | 8 +- NzbDrone.Core/Jobs/UpdateInfoJob.cs | 9 +- NzbDrone.Core/Jobs/UpdateSceneMappingsJob.cs | 9 +- NzbDrone.Core/NzbDrone.Core.csproj | 60 +- NzbDrone.Core/Providers/BackupProvider.cs | 2 - NzbDrone.Core/Providers/MetadataProvider.cs | 172 -- .../Providers/PostDownloadProvider.cs | 11 +- .../Providers/ReferenceDataProvider.cs | 70 - .../Providers/SceneMappingProvider.cs | 114 - .../Providers/Search/DailyEpisodeSearch.cs | 5 +- .../Providers/Search/EpisodeSearch.cs | 5 +- .../Providers/Search/PartialSeasonSearch.cs | 5 +- NzbDrone.Core/Providers/Search/SearchBase.cs | 11 +- .../Providers/TvRageMappingProvider.cs | 9 +- .../Qualities/QualityProfileService.cs | 2 +- NzbDrone.Core/Qualities/QualitySize.cs | 2 +- .../ReferenceData/DailySeriesDataProxy.cs | 48 + .../ReferenceData/DailySeriesService.cs | 62 +- NzbDrone.Core/ReferenceData/SceneMapping.cs | 13 + .../ReferenceData/SceneMappingProvider.cs | 73 + .../ReferenceData/SceneMappingProxy.cs | 49 + .../ReferenceData/SceneMappingRepository.cs | 30 + .../Repository/MetadataDefinition.cs | 17 - NzbDrone.Core/Repository/SceneMapping.cs | 21 - .../Repository/Search/SearchHistory.cs | 13 +- .../Repository/Search/SearchHistoryItem.cs | 6 +- NzbDrone.Core/Tv/SeasonRepository.cs | 2 +- NzbDrone.Core/Tv/Series.cs | 2 +- NzbDrone.Core/Tv/SeriesRepository.cs | 13 + NzbDrone.Core/Tv/SeriesService.cs | 24 +- NzbDrone.sln | 20 - NzbDrone.sln.DotSettings | 1 + 105 files changed, 410 insertions(+), 5340 deletions(-) delete mode 100644 NzbDrone.Core.Test/Framework/SqlCeTest.cs delete mode 100644 NzbDrone.Core.Test/JobTests/EpisodeSearchJobTest.cs delete mode 100644 NzbDrone.Core.Test/MediaFileTests/CleanUpDatabaseFixture.cs delete mode 100644 NzbDrone.Core.Test/ProviderTests/ReferenceDataProviderTest.cs delete mode 100644 NzbDrone.Core/Datastore/ConnectionFactory.cs delete mode 100644 NzbDrone.Core/Datastore/CustomeMapper.cs delete mode 100644 NzbDrone.Core/Datastore/MigrationLogger.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20110707.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20110726.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20110909.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20111011.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20111112.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20111125.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20120118.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20120123.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20120220.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20120227.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20120228.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20120420.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20120430.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20120504.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20120707.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20120727.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20120802.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20120918.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20120919.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20121012.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20121016.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20121122.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20121202.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20121209.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20121218.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20121223.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20121226.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/Migration20130203.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/NzbDroneMigration.cs delete mode 100644 NzbDrone.Core/Datastore/Migrations/SchemaInfo.cs delete mode 100644 NzbDrone.Core/Datastore/MigrationsHelper.cs delete mode 100644 NzbDrone.Core/Datastore/PetaPoco/EpisodeSeasonRelator.cs delete mode 100644 NzbDrone.Core/Datastore/PetaPoco/PetaPoco.cs delete mode 100644 NzbDrone.Core/Datastore/SqlCeProxy.cs delete mode 100644 NzbDrone.Core/Providers/MetadataProvider.cs delete mode 100644 NzbDrone.Core/Providers/ReferenceDataProvider.cs delete mode 100644 NzbDrone.Core/Providers/SceneMappingProvider.cs create mode 100644 NzbDrone.Core/ReferenceData/DailySeriesDataProxy.cs create mode 100644 NzbDrone.Core/ReferenceData/SceneMapping.cs create mode 100644 NzbDrone.Core/ReferenceData/SceneMappingProvider.cs create mode 100644 NzbDrone.Core/ReferenceData/SceneMappingProxy.cs create mode 100644 NzbDrone.Core/ReferenceData/SceneMappingRepository.cs delete mode 100644 NzbDrone.Core/Repository/MetadataDefinition.cs delete mode 100644 NzbDrone.Core/Repository/SceneMapping.cs diff --git a/NzbDrone.Common.Test/PathExtentionFixture.cs b/NzbDrone.Common.Test/PathExtentionFixture.cs index 29885d890..daf43a56f 100644 --- a/NzbDrone.Common.Test/PathExtentionFixture.cs +++ b/NzbDrone.Common.Test/PathExtentionFixture.cs @@ -62,17 +62,6 @@ namespace NzbDrone.Common.Test GetEnviromentProvider().GetConfigPath().Should().BeEquivalentTo(@"C:\NzbDrone\Config.xml"); } - [Test] - public void IISConfig_path_test() - { - GetEnviromentProvider().GetIISConfigPath().Should().BeEquivalentTo(@"C:\NzbDrone\IISExpress\AppServer\applicationhost.config"); - } - - [Test] - public void IISExe_path_test() - { - GetEnviromentProvider().GetIISExe().Should().BeEquivalentTo(@"C:\NzbDrone\IISExpress\IISExpress.exe"); - } [Test] public void NlogConfig_path_test() diff --git a/NzbDrone.Common/PathExtentions.cs b/NzbDrone.Common/PathExtentions.cs index 5edc05e6a..6886816fd 100644 --- a/NzbDrone.Common/PathExtentions.cs +++ b/NzbDrone.Common/PathExtentions.cs @@ -8,16 +8,12 @@ namespace NzbDrone.Common private const string WEB_FOLDER = "NzbDrone.Web\\"; private const string APP_DATA = "App_Data\\"; private const string WEB_BIN = "bin\\"; - public const string IIS_FOLDER = "IISExpress"; - public const string IIS_EXE = "iisexpress.exe"; private const string LOG_CONFIG_FILE = "log.config"; private const string APP_CONFIG_FILE = "config.xml"; public const string NZBDRONE_EXE = "NzbDrone.exe"; - public const string NZBDRONE_SQLCE_DB_FILE = "nzbdrone.sdf"; - public const string LOG_SQLCE_DB_FILE = "log.sdf"; public const string OBJ_DB_FOLDER = "objDb"; private const string BACKUP_ZIP_FILE = "NzbDrone_Backup.zip"; @@ -45,20 +41,8 @@ namespace NzbDrone.Common } - public static string GetIISFolder(this EnvironmentProvider environmentProvider) - { - return Path.Combine(environmentProvider.ApplicationPath, IIS_FOLDER); - } - public static string GetIISExe(this EnvironmentProvider environmentProvider) - { - return Path.Combine(environmentProvider.GetIISFolder(), IIS_EXE); - } - public static string GetIISConfigPath(this EnvironmentProvider environmentProvider) - { - return Path.Combine(environmentProvider.GetIISFolder(), "AppServer", "applicationhost.config"); - } public static string GetWebRoot(this EnvironmentProvider environmentProvider) { @@ -85,16 +69,6 @@ namespace NzbDrone.Common return Path.Combine(environmentProvider.ApplicationPath, APP_CONFIG_FILE); } - public static string GetSqlCeMainDbPath(this EnvironmentProvider environmentProvider) - { - return Path.Combine(environmentProvider.GetAppDataPath(), NZBDRONE_SQLCE_DB_FILE); - } - - public static string GetSqlCeLogDbPath(this EnvironmentProvider environmentProvider) - { - return Path.Combine(environmentProvider.GetAppDataPath(), LOG_SQLCE_DB_FILE); - } - public static string GetObjectDbFolder(this EnvironmentProvider environmentProvider) { return Path.Combine(environmentProvider.GetAppDataPath(), OBJ_DB_FOLDER); diff --git a/NzbDrone.Core.Test/App.config b/NzbDrone.Core.Test/App.config index 1b714ac64..a7d3b0b7f 100644 --- a/NzbDrone.Core.Test/App.config +++ b/NzbDrone.Core.Test/App.config @@ -1,8 +1,5 @@  - -
- @@ -15,11 +12,4 @@ - - - - - - - \ No newline at end of file diff --git a/NzbDrone.Core.Test/CentralDispatchFixture.cs b/NzbDrone.Core.Test/CentralDispatchFixture.cs index 92e65ecde..ff6478a4d 100644 --- a/NzbDrone.Core.Test/CentralDispatchFixture.cs +++ b/NzbDrone.Core.Test/CentralDispatchFixture.cs @@ -36,11 +36,6 @@ namespace NzbDrone.Core.Test public CentralDispatchFixture() { - if (EnvironmentProvider.IsMono) - { - throw new IgnoreException("SqlCe is not supported"); - } - InitLogging(); } @@ -116,11 +111,6 @@ namespace NzbDrone.Core.Test kernel.Resolve().All().Select(c => c.Type).Should().BeEquivalentTo(indexers); } - [Test] - public void metadata_clients_are_initialized() - { - kernel.Resolve().All().Should().HaveSameCount(metadata); - } [Test] public void quality_profile_initialized() diff --git a/NzbDrone.Core.Test/Configuration/ConfigCachingFixture.cs b/NzbDrone.Core.Test/Configuration/ConfigCachingFixture.cs index 19922c002..b4893b8b5 100644 --- a/NzbDrone.Core.Test/Configuration/ConfigCachingFixture.cs +++ b/NzbDrone.Core.Test/Configuration/ConfigCachingFixture.cs @@ -5,7 +5,7 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.Configuration; using NzbDrone.Core.Test.Framework; -using PetaPoco; + namespace NzbDrone.Core.Test.Configuration { diff --git a/NzbDrone.Core.Test/Framework/SqlCeTest.cs b/NzbDrone.Core.Test/Framework/SqlCeTest.cs deleted file mode 100644 index 3d5a5bf62..000000000 --- a/NzbDrone.Core.Test/Framework/SqlCeTest.cs +++ /dev/null @@ -1,146 +0,0 @@ -using System; -using System.IO; -using NUnit.Framework; -using NzbDrone.Common; -using NzbDrone.Core.Configuration; -using NzbDrone.Core.Datastore; -using NzbDrone.Core.Model.Notification; -using NzbDrone.Core.Providers.Core; -using NzbDrone.Test.Common; -using PetaPoco; - -namespace NzbDrone.Core.Test.Framework -{ - public abstract class SqlCeTest : CoreTest - { - private string _dbTemplateName; - - [SetUp] - public void CoreTestSetup() - { - if (EnvironmentProvider.IsMono) - { - throw new IgnoreException("SqlCe is not supported in mono."); - } - - if (NCrunch.Framework.NCrunchEnvironment.NCrunchIsResident()) - { - _dbTemplateName = Path.Combine(Path.GetTempPath(), Path.GetTempFileName()) + ".sdf"; - } - else - { - _dbTemplateName = "db_template.sdf"; - } - - CreateDataBaseTemplate(); - } - - private IDatabase GetEmptyDatabase(string fileName = "") - { - Console.WriteLine("====================DataBase===================="); - Console.WriteLine("Cloning database from template."); - - if (String.IsNullOrWhiteSpace(fileName)) - { - fileName = Guid.NewGuid() + ".sdf"; - } - - File.Copy(_dbTemplateName, fileName); - - var connectionString = ConnectionFactory.GetConnectionString(fileName); - var database = ConnectionFactory.GetPetaPocoDb(connectionString); - - Console.WriteLine("====================DataBase===================="); - Console.WriteLine(); - Console.WriteLine(); - - return database; - } - - private void CreateDataBaseTemplate() - { - Console.WriteLine("Creating an empty PetaPoco database"); - var connectionString = ConnectionFactory.GetConnectionString(_dbTemplateName); - var database = ConnectionFactory.GetPetaPocoDb(connectionString); - database.Dispose(); - } - - - - private IDatabase _db; - protected IDatabase Db - { - get - { - if (_db == null) - throw new InvalidOperationException("Test db doesn't exists. Make sure you call WithRealDb() if you intend to use an actual database."); - - return _db; - } - } - - - - protected void WithRealDb() - { - if (EnvironmentProvider.IsMono) - { - throw new IgnoreException("SqlCe is not supported in mono."); - } - - _db = GetEmptyDatabase(); - Mocker.SetConstant(Db); - } - - - [TearDown] - public void CoreTestTearDown() - { - ConfigService.ClearCache(); - - if (EnvironmentProvider.IsMono) - { - return; - } - - if (_db != null && _db.Connection != null && File.Exists(_db.Connection.Database)) - { - var file = _db.Connection.Database; - _db.Dispose(); - try - { - File.Delete(file); - - } - catch (IOException) { } - } - } - } - - public abstract class SqlCeTest : SqlCeTest where TSubject : class - { - - private TSubject _subject; - - - protected TSubject Subject - { - get - { - if (_subject == null) - { - _subject = Mocker.Resolve(); - } - - return _subject; - - } - } - - - protected void InitiateSubject() - { - _subject = Mocker.Resolve(); - } - } -} diff --git a/NzbDrone.Core.Test/Framework/TestDbHelper.cs b/NzbDrone.Core.Test/Framework/TestDbHelper.cs index 8ff54d2fa..8d87c13e9 100644 --- a/NzbDrone.Core.Test/Framework/TestDbHelper.cs +++ b/NzbDrone.Core.Test/Framework/TestDbHelper.cs @@ -9,7 +9,7 @@ using NzbDrone.Common; using NzbDrone.Core.Datastore; using NzbDrone.Core.Providers.Core; using NzbDrone.Core.Repository; -using PetaPoco; + namespace NzbDrone.Core.Test.Framework { diff --git a/NzbDrone.Core.Test/JobTests/EpisodeSearchJobTest.cs b/NzbDrone.Core.Test/JobTests/EpisodeSearchJobTest.cs deleted file mode 100644 index 4dfe89779..000000000 --- a/NzbDrone.Core.Test/JobTests/EpisodeSearchJobTest.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; - -using Moq; -using NUnit.Framework; -using NzbDrone.Core.Jobs; -using NzbDrone.Core.Model.Notification; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Test.Common.AutoMoq; - -namespace NzbDrone.Core.Test.JobTests -{ - [TestFixture] - public class EpisodeSearchJobTest:SqlCeTest - { - [TestCase(0)] - [TestCase(-1)] - [TestCase(-100)] - [ExpectedException(typeof(ArgumentException))] - public void start_target_id_less_than_0_throws_exception(int target) - { - WithStrictMocker(); - Mocker.Resolve().Start(new ProgressNotification("Test"), new { EpisodeId = target }); - } - - [TestCase(-1)] - [TestCase(-100)] - [ExpectedException(typeof(ArgumentException))] - public void start_secondary_target_id_less_than_0_throws_exception(int target) - { - WithStrictMocker(); - Mocker.Resolve().Start(new ProgressNotification("Test"), new { SeriesId = 1, SeasonNumber = target }); - } - } -} diff --git a/NzbDrone.Core.Test/JobTests/RenameSeasonJobFixture.cs b/NzbDrone.Core.Test/JobTests/RenameSeasonJobFixture.cs index 457b5ca9f..b690492be 100644 --- a/NzbDrone.Core.Test/JobTests/RenameSeasonJobFixture.cs +++ b/NzbDrone.Core.Test/JobTests/RenameSeasonJobFixture.cs @@ -75,21 +75,6 @@ namespace NzbDrone.Core.Test.JobTests ExceptionVerification.ExpectedWarns(1); } - [Test] - public void should_return_if_no_episodes_are_moved() - { - Mocker.Resolve().Start(_testNotification, new { SeriesId = _series.Id, SeasonNumber = 5 }); - - Mocker.GetMock().Verify(v => v.RemoveForEpisodeFiles(It.IsAny>()), Times.Never()); - } - - [Test] - public void should_return_process_metadata_if_files_are_moved() - { - WithMovedFiles(); - Mocker.Resolve().Start(_testNotification, new { SeriesId = _series.Id, SeasonNumber = 5 }); - - Mocker.GetMock().Verify(v => v.RemoveForEpisodeFiles(It.IsAny>()), Times.Once()); - } + } } diff --git a/NzbDrone.Core.Test/MediaFileTests/CleanUpDatabaseFixture.cs b/NzbDrone.Core.Test/MediaFileTests/CleanUpDatabaseFixture.cs deleted file mode 100644 index b56a8b313..000000000 --- a/NzbDrone.Core.Test/MediaFileTests/CleanUpDatabaseFixture.cs +++ /dev/null @@ -1,132 +0,0 @@ -using System; -using System.Linq; -using FizzWare.NBuilder; -using FluentAssertions; -using NUnit.Framework; -using NzbDrone.Core.Configuration; -using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Tv; -using NzbDrone.Core.Model; -using NzbDrone.Core.Test.Framework; - -namespace NzbDrone.Core.Test.MediaFileTests -{ - [TestFixture] - public class CleanUpDatabaseFixture : SqlCeTest - { - - [SetUp] - public void Setup() - { - WithRealDb(); - } - - private void WithAutoIgnore(bool autoIgnore) - { - - Mocker.GetMock() - .SetupGet(c => c.AutoIgnorePreviouslyDownloadedEpisodes).Returns(autoIgnore); - } - - - - [Test] - public void CleanUpDatabse_should_detach_none_existing_file_from_episodes_with_auto_ignore() - { - WithAutoIgnore(true); - - var episodes = Builder.CreateListOfSize(3) - .All().With(c => c.GrabDate = DateTime.Now) - .And(c => c.Ignored = false) - .And(c => c.PostDownloadStatus = PostDownloadStatusType.NoError) - .Build(); - - - Db.InsertMany(episodes); - - //Act - var result = Db.Fetch(); - - //Assert - result.Should().HaveSameCount(episodes); - result.Should().OnlyContain(e => e.EpisodeFileId == 0); - result.Should().OnlyContain(e => e.PostDownloadStatus == PostDownloadStatusType.Unknown); - result.Should().OnlyContain(e => e.Ignored); - result.Should().OnlyContain(e => e.GrabDate == null); - } - - [Test] - public void CleanUpDatabse_should_detach_none_existing_file_from_episodes_with_no_auto_ignore() - { - WithAutoIgnore(false); - - var episodes = Builder.CreateListOfSize(3) - .All().With(c => c.GrabDate = DateTime.Now) - .And(c => c.PostDownloadStatus = PostDownloadStatusType.NoError) - .TheFirst(2).With(c => c.Ignored = true) - .TheLast(1).With(c => c.Ignored = false) - .Build(); - - - Db.InsertMany(episodes); - - //Act - var result = Db.Fetch(); - - //Assert - result.Should().HaveSameCount(episodes); - result.Should().OnlyContain(e => e.EpisodeFileId == 0); - result.Should().OnlyContain(e => e.PostDownloadStatus == PostDownloadStatusType.Unknown); - result.Should().OnlyContain(e => e.GrabDate == null); - result.Should().Contain(c => c.Ignored == true); - result.Should().Contain(c => c.Ignored == false); - } - - [Test] - public void CleanUpDatabse_should_not_change_episodes_with_no_file_id() - { - //Setup - var episodes = Builder.CreateListOfSize(3) - .All().With(c => c.GrabDate = DateTime.Now) - .And(c => c.Ignored = false) - .And(c => c.PostDownloadStatus = PostDownloadStatusType.NoError) - .Build(); - - Db.InsertMany(episodes); - - //Act - var result = Db.Fetch(); - - //Assert - result.Should().HaveSameCount(episodes); - result.Should().OnlyContain(e => e.EpisodeFileId == 0); - result.Should().NotContain(e => e.PostDownloadStatus == PostDownloadStatusType.Unknown); - result.Should().NotContain(e => e.Ignored); - result.Should().NotContain(e => e.GrabDate == null); - } - - - [Test] - public void DeleteOrphanedEpisodeFiles() - { - //Setup - var episodeFiles = Builder - .CreateListOfSize(10) - .All() - .With(e => e.Quality = Quality.DVD) - .Build(); - var episodes = Builder.CreateListOfSize(5).Build(); - - Db.InsertMany(episodes); - Db.InsertMany(episodeFiles); - - //Act - var result = Db.Fetch(); - - //Assert - result.Should().HaveCount(5); - result.Should().OnlyContain(e => e.Id > 0); - } - } -} diff --git a/NzbDrone.Core.Test/MediaFileTests/MediaFileServiceTest.cs b/NzbDrone.Core.Test/MediaFileTests/MediaFileServiceTest.cs index 34bf42817..a5db8ec50 100644 --- a/NzbDrone.Core.Test/MediaFileTests/MediaFileServiceTest.cs +++ b/NzbDrone.Core.Test/MediaFileTests/MediaFileServiceTest.cs @@ -19,7 +19,7 @@ namespace NzbDrone.Core.Test.MediaFileTests { [TestFixture] // ReSharper disable InconsistentNaming - public class MediaFileServiceTest : SqlCeTest + public class MediaFileServiceTest : ObjectDbTest { [Test] public void get_series_files() @@ -36,8 +36,6 @@ namespace NzbDrone.Core.Test.MediaFileTests - WithRealDb(); - Db.InsertMany(firstSeriesFiles); Db.InsertMany(secondSeriesFiles); @@ -66,7 +64,6 @@ namespace NzbDrone.Core.Test.MediaFileTests .Build(); - WithRealDb(); Db.InsertMany(firstSeriesFiles); Db.InsertMany(secondSeriesFiles); @@ -148,23 +145,18 @@ namespace NzbDrone.Core.Test.MediaFileTests .Build(); - WithRealDb(); Db.InsertMany(episodeFiles); //Act Mocker.Resolve().Delete(1); - var result = Db.Fetch(); - //Assert - result.Should().HaveCount(9); - result.Should().NotContain(e => e.Id == 1); + } [Test] public void GetFileByPath_should_return_null_if_file_does_not_exist_in_database() { //Setup - WithRealDb(); //Act var result = Mocker.Resolve().GetFileByPath(@"C:\Test\EpisodeFile.avi"); @@ -179,7 +171,6 @@ namespace NzbDrone.Core.Test.MediaFileTests var path = @"C:\Test\EpisodeFile.avi"; //Setup - WithRealDb(); var episodeFile = Builder.CreateNew() .With(c => c.Quality = Quality.SDTV) .With(f => f.Path = path.NormalizePath()) diff --git a/NzbDrone.Core.Test/NzbDrone.Core.Test.csproj b/NzbDrone.Core.Test/NzbDrone.Core.Test.csproj index f1adc1f45..12bbdb5a2 100644 --- a/NzbDrone.Core.Test/NzbDrone.Core.Test.csproj +++ b/NzbDrone.Core.Test/NzbDrone.Core.Test.csproj @@ -199,8 +199,6 @@ - - @@ -209,7 +207,6 @@ - @@ -233,7 +230,6 @@ - diff --git a/NzbDrone.Core.Test/ProviderTests/PostDownloadProviderTests/ProcessDownloadFixture.cs b/NzbDrone.Core.Test/ProviderTests/PostDownloadProviderTests/ProcessDownloadFixture.cs index a43d92355..20edfd049 100644 --- a/NzbDrone.Core.Test/ProviderTests/PostDownloadProviderTests/ProcessDownloadFixture.cs +++ b/NzbDrone.Core.Test/ProviderTests/PostDownloadProviderTests/ProcessDownloadFixture.cs @@ -303,7 +303,6 @@ namespace NzbDrone.Core.Test.ProviderTests.PostDownloadProviderTests Mocker.GetMock().Setup(s => s.DeleteFolder(droppedFolder.FullName, true)); Mocker.GetMock().Setup(s => s.FolderExists(fakeSeries.Path)).Returns(true); Mocker.GetMock().Setup(s => s.IsFolderLocked(droppedFolder.FullName)).Returns(false); - Mocker.GetMock().Setup(s => s.CreateForEpisodeFiles(It.IsAny>())); //Act Mocker.Resolve().ProcessDownload(droppedFolder); diff --git a/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/CleanupFixture.cs b/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/CleanupFixture.cs index 73bae6228..91e1c3287 100644 --- a/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/CleanupFixture.cs +++ b/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/CleanupFixture.cs @@ -17,7 +17,7 @@ using NzbDrone.Core.Providers.Core; using NzbDrone.Core.Repository; using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common.AutoMoq; -using PetaPoco; + using TvdbLib.Data; namespace NzbDrone.Core.Test.ProviderTests.RecycleBinProviderTests diff --git a/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteDirectoryFixture.cs b/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteDirectoryFixture.cs index 35da6fbc8..eaa0c90ed 100644 --- a/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteDirectoryFixture.cs +++ b/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteDirectoryFixture.cs @@ -17,7 +17,7 @@ using NzbDrone.Core.Providers.Core; using NzbDrone.Core.Repository; using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common.AutoMoq; -using PetaPoco; + using TvdbLib.Data; namespace NzbDrone.Core.Test.ProviderTests.RecycleBinProviderTests diff --git a/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteFileFixture.cs b/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteFileFixture.cs index 5c334642e..586d8e12d 100644 --- a/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteFileFixture.cs +++ b/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteFileFixture.cs @@ -17,7 +17,7 @@ using NzbDrone.Core.Providers.Core; using NzbDrone.Core.Repository; using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common.AutoMoq; -using PetaPoco; + using TvdbLib.Data; namespace NzbDrone.Core.Test.ProviderTests.RecycleBinProviderTests diff --git a/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/EmptyFixture.cs b/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/EmptyFixture.cs index 4f675d522..e6c6086d2 100644 --- a/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/EmptyFixture.cs +++ b/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/EmptyFixture.cs @@ -17,7 +17,7 @@ using NzbDrone.Core.Providers.Core; using NzbDrone.Core.Repository; using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common.AutoMoq; -using PetaPoco; + using TvdbLib.Data; namespace NzbDrone.Core.Test.ProviderTests.RecycleBinProviderTests diff --git a/NzbDrone.Core.Test/ProviderTests/ReferenceDataProviderTest.cs b/NzbDrone.Core.Test/ProviderTests/ReferenceDataProviderTest.cs deleted file mode 100644 index ccecf58a1..000000000 --- a/NzbDrone.Core.Test/ProviderTests/ReferenceDataProviderTest.cs +++ /dev/null @@ -1,212 +0,0 @@ -using System; -using System.Linq; -using System.Net; -using FizzWare.NBuilder; -using FluentAssertions; -using Moq; -using NUnit.Framework; -using NzbDrone.Common; -using NzbDrone.Core.Configuration; -using NzbDrone.Core.Tv; -using NzbDrone.Core.Providers; -using NzbDrone.Core.Providers.Core; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Test.Common; - -namespace NzbDrone.Core.Test.ProviderTests -{ - [TestFixture] - // ReSharper disable InconsistentNaming - public class ReferenceDataProviderTest : SqlCeTest - { - private const string validSeriesIds = "[1,2,3,4,5]"; - private const string invalidSeriesIds = "[1,2,NaN,4,5]"; - - private const string url = "http://services.nzbdrone.com/DailySeries/AllIds"; - - [SetUp] - public void Setup() - { - Mocker.GetMock().SetupGet(s => s.ServiceRootUrl) - .Returns("http://services.nzbdrone.com"); - } - - - [Test] - public void GetDailySeriesIds_should_return_list_of_int_when_all_are_valid() - { - //Setup - Mocker.GetMock().Setup(s => s.DownloadString(url)) - .Returns(validSeriesIds); - - //Act - var result = Mocker.Resolve().GetDailySeriesIds(); - - //Assert - result.Should().HaveCount(5); - } - - [Test] - public void GetDailySeriesIds_should_return_empty_list_when_unable_to_parse() - { - //Setup - Mocker.GetMock().Setup(s => s.DownloadString(url)) - .Returns(invalidSeriesIds); - - //Act - var result = Mocker.Resolve().GetDailySeriesIds(); - - //Assert - result.Should().BeEmpty(); - ExceptionVerification.ExpectedWarns(1); - } - - [Test] - public void GetDailySeriesIds_should_return_empty_list_of_int_when_server_is_unavailable() - { - //Setup - Mocker.GetMock().Setup(s => s.DownloadString(url)) - .Throws(new Exception()); - - //Act - var result = Mocker.Resolve().GetDailySeriesIds(); - - //Assert - result.Should().HaveCount(0); - ExceptionVerification.ExpectedWarns(1); - } - - [Test] - public void IsDailySeries_should_return_true() - { - //Setup - Mocker.GetMock().Setup(s => s.DownloadString(url)) - .Returns(validSeriesIds); - - //Act - var result = Mocker.Resolve().IsSeriesDaily(1); - - //Assert - result.Should().BeTrue(); - } - - [Test] - public void IsDailySeries_should_return_false() - { - //Setup - Mocker.GetMock().Setup(s => s.DownloadString(url)) - .Returns(validSeriesIds); - - //Act - var result = Mocker.Resolve().IsSeriesDaily(10); - - //Assert - result.Should().BeFalse(); - } - - [Test] - public void UpdateDailySeries_should_update_series_that_match_daily_series_list() - { - WithRealDb(); - - var fakeSeries = Builder.CreateListOfSize(5) - .All() - .With(s => s.SeriesType = SeriesType.Standard) - .Build(); - - Db.InsertMany(fakeSeries); - - //Setup - Mocker.GetMock().Setup(s => s.DownloadString(url)) - .Returns(validSeriesIds); - - //Act - Mocker.Resolve().UpdateDailySeries(); - - //Assert - var result = Db.Fetch(); - - result.Where(s => s.SeriesType == SeriesType.Daily).Should().HaveCount(5); - } - - [Test] - public void UpdateDailySeries_should_update_series_should_skip_series_that_dont_match() - { - WithRealDb(); - - var fakeSeries = Builder.CreateListOfSize(5) - .All() - .With(s => s.SeriesType = SeriesType.Standard) - .TheFirst(1) - .With(s => s.Id = 10) - .TheNext(1) - .With(s => s.Id = 11) - .TheNext(1) - .With(s => s.Id = 12) - .Build(); - - Db.InsertMany(fakeSeries); - - //Setup - Mocker.GetMock().Setup(s => s.DownloadString(url)) - .Returns(validSeriesIds); - - //Act - Mocker.Resolve().UpdateDailySeries(); - - //Assert - var result = Db.Fetch(); - - result.Where(s => s.SeriesType == SeriesType.Standard).Should().HaveCount(3); - result.Where(s => s.SeriesType == SeriesType.Daily).Should().HaveCount(2); - } - - [Test] - public void UpdateDailySeries_should_update_series_should_not_overwrite_existing_isDaily() - { - WithRealDb(); - - var fakeSeries = Builder.CreateListOfSize(5) - .All() - .With(s => s.SeriesType = SeriesType.Standard) - .TheFirst(1) - .With(s => s.Id = 10) - .With(s => s.SeriesType = SeriesType.Daily) - .TheNext(1) - .With(s => s.Id = 11) - .TheNext(1) - .With(s => s.Id = 12) - .Build(); - - Db.InsertMany(fakeSeries); - - //Setup - Mocker.GetMock().Setup(s => s.DownloadString(url)) - .Returns(validSeriesIds); - - //Act - Mocker.Resolve().UpdateDailySeries(); - - //Assert - var result = Db.Fetch(); - - result.Where(s => s.SeriesType == SeriesType.Daily).Should().HaveCount(3); - result.Where(s => s.SeriesType == SeriesType.Standard).Should().HaveCount(2); - } - - [Test] - public void broken_service_should_not_cause_this_call_to_fail() - { - WithRealDb(); - - Mocker.GetMock().Setup(s => s.DownloadString(It.IsAny())) - .Throws(new WebException()) - .Verifiable(); - - Mocker.Resolve().UpdateDailySeries(); - - ExceptionVerification.ExpectedWarns(1); - Mocker.VerifyAllMocks(); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core.Test/ProviderTests/SceneMappingProviderTest.cs b/NzbDrone.Core.Test/ProviderTests/SceneMappingProviderTest.cs index a5017ec5d..65b49f8e5 100644 --- a/NzbDrone.Core.Test/ProviderTests/SceneMappingProviderTest.cs +++ b/NzbDrone.Core.Test/ProviderTests/SceneMappingProviderTest.cs @@ -7,17 +7,14 @@ using Moq; using NUnit.Framework; using NzbDrone.Common; using NzbDrone.Core.Configuration; -using NzbDrone.Core.Providers; -using NzbDrone.Core.Providers.Core; -using NzbDrone.Core.Repository; +using NzbDrone.Core.ReferenceData; using NzbDrone.Core.Test.Framework; -using NzbDrone.Test.Common.AutoMoq; namespace NzbDrone.Core.Test.ProviderTests { [TestFixture] // ReSharper disable InconsistentNaming - public class SceneMappingProviderTest : SqlCeTest + public class SceneMappingProviderTest : ObjectDbTest { private const string SceneMappingUrl = "http://services.nzbdrone.com/SceneMapping/Active"; @@ -27,7 +24,6 @@ namespace NzbDrone.Core.Test.ProviderTests Mocker.GetMock().SetupGet(s => s.ServiceRootUrl) .Returns("http://services.nzbdrone.com"); - WithRealDb(); } private void WithValidJson() @@ -47,12 +43,11 @@ namespace NzbDrone.Core.Test.ProviderTests [Test] public void GetSceneName_exists() { - WithRealDb(); //Setup var fakeMap = Builder.CreateNew() .With(f => f.CleanTitle = "laworder") - .With(f => f.SeriesId = 12345) + .With(f => f.TvdbId = 12345) .With(f => f.SceneName = "Law and Order") .With(f => f.SeasonNumber = -1) .Build(); @@ -60,7 +55,7 @@ namespace NzbDrone.Core.Test.ProviderTests Db.Insert(fakeMap); //Act - var sceneName = Mocker.Resolve().GetSceneName(fakeMap.SeriesId); + var sceneName = Mocker.Resolve().GetSceneName(fakeMap.TvdbId); //Assert Assert.AreEqual(fakeMap.SceneName, sceneName); @@ -69,11 +64,10 @@ namespace NzbDrone.Core.Test.ProviderTests [Test] public void GetSeriesId_exists() { - WithRealDb(); //Setup var fakeMap = Builder.CreateNew() - .With(f => f.SeriesId = 12345) + .With(f => f.TvdbId = 12345) .With(f => f.SceneName = "Law and Order") .With(f => f.SceneName = "laworder") .Build(); @@ -82,20 +76,19 @@ namespace NzbDrone.Core.Test.ProviderTests Db.Insert(fakeMap); //Act - var seriesId = Mocker.Resolve().GetSeriesId(fakeMap.CleanTitle); + var seriesId = Mocker.Resolve().GetTvDbId(fakeMap.CleanTitle); //Assert - Assert.AreEqual(fakeMap.SeriesId, seriesId); + Assert.AreEqual(fakeMap.TvdbId, seriesId); } [Test] public void GetSceneName_null() { - WithRealDb(); //Setup var fakeMap = Builder.CreateNew() - .With(f => f.SeriesId = 12345) + .With(f => f.TvdbId = 12345) .With(f => f.SceneName = "Law and Order") .With(f => f.SceneName = "laworder") .Build(); @@ -104,7 +97,7 @@ namespace NzbDrone.Core.Test.ProviderTests Db.Insert(fakeMap); //Act - var sceneName = Mocker.Resolve().GetSceneName(54321); + var sceneName = Mocker.Resolve().GetSceneName(54321); //Assert Assert.AreEqual(null, sceneName); @@ -113,11 +106,10 @@ namespace NzbDrone.Core.Test.ProviderTests [Test] public void GetSeriesId_null() { - WithRealDb(); //Setup var fakeMap = Builder.CreateNew() - .With(f => f.SeriesId = 12345) + .With(f => f.TvdbId = 12345) .With(f => f.SceneName = "Law and Order") .With(f => f.CleanTitle = "laworder") .Build(); @@ -125,7 +117,7 @@ namespace NzbDrone.Core.Test.ProviderTests Db.Insert(fakeMap); //Act - var seriesId = Mocker.Resolve().GetSeriesId("notlaworder"); + var seriesId = Mocker.Resolve().GetTvDbId("notlaworder"); //Assert Assert.AreEqual(null, seriesId); @@ -134,20 +126,19 @@ namespace NzbDrone.Core.Test.ProviderTests [Test] public void GetSceneName_multiple_clean_names() { - WithRealDb(); //Test that ensures a series with clean names (office, officeus) can be looked up by seriesId //Setup var fakeMap = Builder.CreateNew() .With(f => f.CleanTitle = "office") - .With(f => f.SeriesId = 12345) + .With(f => f.TvdbId = 12345) .With(f => f.SceneName = "The Office") .With(f => f.SeasonNumber = -1) .Build(); var fakeMap2 = Builder.CreateNew() .With(f => f.CleanTitle = "officeus") - .With(f => f.SeriesId = 12345) + .With(f => f.TvdbId = 12345) .With(f => f.SceneName = "The Office") .With(f => f.SeasonNumber = -1) .Build(); @@ -158,7 +149,7 @@ namespace NzbDrone.Core.Test.ProviderTests Db.Insert(fakeMap2); //Act - var sceneName = Mocker.Resolve().GetSceneName(fakeMap.SeriesId); + var sceneName = Mocker.Resolve().GetSceneName(fakeMap.TvdbId); //Assert Assert.AreEqual(fakeMap.SceneName, sceneName); @@ -167,10 +158,10 @@ namespace NzbDrone.Core.Test.ProviderTests [Test] public void GetSceneName_should_be_null_when_seasonNumber_does_not_match() { - WithRealDb(); + var fakeMap = Builder.CreateNew() - .With(f => f.SeriesId = 12345) + .With(f => f.TvdbId = 12345) .With(f => f.SceneName = "Law and Order") .With(f => f.SceneName = "laworder") .With(f => f.SeasonNumber = 10) @@ -178,7 +169,7 @@ namespace NzbDrone.Core.Test.ProviderTests Db.Insert(fakeMap); - Mocker.Resolve().GetSceneName(54321, 5).Should().BeNull(); + Mocker.Resolve().GetSceneName(54321, 5).Should().BeNull(); } [Test] @@ -187,12 +178,10 @@ namespace NzbDrone.Core.Test.ProviderTests WithValidJson(); //Act - Mocker.Resolve().UpdateMappings(); + Mocker.Resolve().UpdateMappings(); //Assert Mocker.Verify(v => v.DownloadString(SceneMappingUrl), Times.Once()); - var result = Db.Fetch(); - result.Should().HaveCount(5); } [Test] @@ -200,7 +189,7 @@ namespace NzbDrone.Core.Test.ProviderTests { //Setup var fakeMap = Builder.CreateNew() - .With(f => f.SeriesId = 12345) + .With(f => f.TvdbId = 12345) .With(f => f.SceneName = "Law and Order") .With(f => f.SceneName = "laworder") .Build(); @@ -209,12 +198,10 @@ namespace NzbDrone.Core.Test.ProviderTests Db.Insert(fakeMap); //Act - Mocker.Resolve().UpdateMappings(); + Mocker.Resolve().UpdateMappings(); //Assert Mocker.Verify(v => v.DownloadString(SceneMappingUrl), Times.Once()); - var result = Db.Fetch(); - result.Should().HaveCount(5); } [Test] @@ -222,7 +209,7 @@ namespace NzbDrone.Core.Test.ProviderTests { //Setup var fakeMap = Builder.CreateNew() - .With(f => f.SeriesId = 12345) + .With(f => f.TvdbId = 12345) .With(f => f.SceneName = "Law and Order") .With(f => f.SceneName = "laworder") .Build(); @@ -231,46 +218,11 @@ namespace NzbDrone.Core.Test.ProviderTests Db.Insert(fakeMap); //Act - Mocker.Resolve().UpdateMappings(); + Mocker.Resolve().UpdateMappings(); //Assert Mocker.Verify(v => v.DownloadString(SceneMappingUrl), Times.Once()); - var result = Db.Fetch(); - result.Should().HaveCount(1); } - [Test] - public void UpdateIfEmpty_should_not_update_if_count_is_not_zero() - { - //Setup - var fakeMap = Builder.CreateNew() - .With(f => f.SeriesId = 12345) - .With(f => f.SceneName = "Law and Order") - .With(f => f.SceneName = "laworder") - .Build(); - - Db.Insert(fakeMap); - - //Act - Mocker.Resolve().UpdateIfEmpty(); - - //Assert - Mocker.Verify(v => v.DownloadString(SceneMappingUrl), Times.Never()); - } - - [Test] - public void UpdateIfEmpty_should_update_if_count_is_zero() - { - //Setup - WithValidJson(); - - //Act - Mocker.Resolve().UpdateIfEmpty(); - - //Assert - Mocker.Verify(v => v.DownloadString(SceneMappingUrl), Times.Once()); - var result = Db.Fetch(); - result.Should().HaveCount(5); - } } } diff --git a/NzbDrone.Core.Test/ProviderTests/SearchTests/GetSearchTitleFixture.cs b/NzbDrone.Core.Test/ProviderTests/SearchTests/GetSearchTitleFixture.cs index 5f3ae7b74..1cdde80d1 100644 --- a/NzbDrone.Core.Test/ProviderTests/SearchTests/GetSearchTitleFixture.cs +++ b/NzbDrone.Core.Test/ProviderTests/SearchTests/GetSearchTitleFixture.cs @@ -5,6 +5,7 @@ using System.Text; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; +using NzbDrone.Core.ReferenceData; using NzbDrone.Core.Tv; using NzbDrone.Core.Providers; using NzbDrone.Core.Providers.Search; @@ -28,7 +29,7 @@ namespace NzbDrone.Core.Test.ProviderTests.SearchTests private void WithSceneMapping() { - Mocker.GetMock() + Mocker.GetMock() .Setup(s => s.GetSceneName(_series.Id, -1)) .Returns("Hawaii Five 0 2010"); } @@ -52,7 +53,7 @@ namespace NzbDrone.Core.Test.ProviderTests.SearchTests [Test] public void should_return_season_scene_name_when_one_exists() { - Mocker.GetMock() + Mocker.GetMock() .Setup(s => s.GetSceneName(_series.Id, 5)) .Returns("Hawaii Five 0 2010 - Season 5"); @@ -85,7 +86,7 @@ namespace NzbDrone.Core.Test.ProviderTests.SearchTests { _series.Title = input; - Mocker.GetMock() + Mocker.GetMock() .Setup(s => s.GetSceneName(_series.Id, -1)) .Returns(""); diff --git a/NzbDrone.Core.Test/ProviderTests/SearchTests/TestSearch.cs b/NzbDrone.Core.Test/ProviderTests/SearchTests/TestSearch.cs index 19a0cddc7..b75e148da 100644 --- a/NzbDrone.Core.Test/ProviderTests/SearchTests/TestSearch.cs +++ b/NzbDrone.Core.Test/ProviderTests/SearchTests/TestSearch.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using NLog; using NzbDrone.Core.Download; using NzbDrone.Core.Indexers; +using NzbDrone.Core.ReferenceData; using NzbDrone.Core.Tv; using NzbDrone.Core.Model; using NzbDrone.Core.Providers; @@ -20,9 +21,9 @@ namespace NzbDrone.Core.Test.ProviderTests.SearchTests private static readonly Logger logger = LogManager.GetCurrentClassLogger(); public TestSearch(ISeriesService seriesService, IEpisodeService episodeService, DownloadProvider downloadProvider, - IIndexerService indexerService, SceneMappingProvider sceneMappingProvider, + IIndexerService indexerService, SceneMappingService sceneMappingService, AllowedDownloadSpecification allowedDownloadSpecification, ISeriesRepository seriesRepository) - : base(seriesService, seriesRepository, episodeService, downloadProvider, indexerService, sceneMappingProvider, + : base(seriesService, seriesRepository, episodeService, downloadProvider, indexerService, sceneMappingService, allowedDownloadSpecification) { } diff --git a/NzbDrone.Core.Test/ProviderTests/TvRageMappingProviderTests/FindMatchingTvRageSeriesFixture.cs b/NzbDrone.Core.Test/ProviderTests/TvRageMappingProviderTests/FindMatchingTvRageSeriesFixture.cs index d6c24d4de..d3f9f2b7b 100644 --- a/NzbDrone.Core.Test/ProviderTests/TvRageMappingProviderTests/FindMatchingTvRageSeriesFixture.cs +++ b/NzbDrone.Core.Test/ProviderTests/TvRageMappingProviderTests/FindMatchingTvRageSeriesFixture.cs @@ -5,6 +5,7 @@ using System.Text; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; +using NzbDrone.Core.ReferenceData; using NzbDrone.Core.Tv; using NzbDrone.Core.Model.TvRage; using NzbDrone.Core.Providers; @@ -49,7 +50,7 @@ namespace NzbDrone.Core.Test.ProviderTests.TvRageMappingProviderTests .Setup(s => s.GetEpisode(_series.Id, 1, 1)) .Returns(_episode); - Mocker.GetMock() + Mocker.GetMock() .Setup(s => s.GetCleanName(_series.Id)) .Returns(""); diff --git a/NzbDrone.Core.Test/TvTests/EpisodeProviderTests/EpisodeProviderTest.cs b/NzbDrone.Core.Test/TvTests/EpisodeProviderTests/EpisodeProviderTest.cs index 4df8ce673..c457b9fd1 100644 --- a/NzbDrone.Core.Test/TvTests/EpisodeProviderTests/EpisodeProviderTest.cs +++ b/NzbDrone.Core.Test/TvTests/EpisodeProviderTests/EpisodeProviderTest.cs @@ -1,4 +1,5 @@ -// ReSharper disable RedundantUsingDirective +/* +// ReSharper disable RedundantUsingDirective using System; using System.Collections.Generic; @@ -16,19 +17,19 @@ using NzbDrone.Core.Model; using NzbDrone.Core.Providers; using NzbDrone.Core.Providers.Core; using NzbDrone.Core.Test.Framework; -using PetaPoco; + using TvdbLib.Data; namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests { [TestFixture] // ReSharper disable InconsistentNaming - public class EpisodeProviderTest : SqlCeTest + public class EpisodeProviderTest : ObjectDbTest { [Test] public void GetEpisodes_exists() { - WithRealDb(); + var fakeSeries = Builder.CreateNew().Build(); var fakeEpisodes = Builder.CreateListOfSize(5) @@ -48,7 +49,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void GetEpisodes_by_season_episode_exists() { - WithRealDb(); + var fakeSeries = Builder.CreateNew() .With(s => s.Id = 1) @@ -72,7 +73,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void GetEpisodes_by_season_episode_doesnt_exists() { - WithRealDb(); + //Act var episode = Mocker.Resolve().GetEpisode(1, 1, 1); @@ -84,7 +85,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void GetEpisode_with_EpisodeFile() { - WithRealDb(); + var fakeSeries = Builder.CreateNew().Build(); var fakeFile = Builder.CreateNew().With(f => f.Id).With(c => c.Quality = Quality.SDTV).Build(); @@ -108,7 +109,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [ExpectedException(typeof(InvalidOperationException), ExpectedMessage = "Sequence contains no elements")] public void GetEpisodes_invalid_series() { - WithRealDb(); + Mocker.Resolve(); @@ -126,7 +127,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void GetEpisodesBySeason_success() { - WithRealDb(); + var fakeSeries = Builder.CreateNew() .With(s => s.Id = 12) @@ -165,7 +166,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests var fakeSeries = Builder.CreateNew().With(c => c.Id = seriesId).Build(); - WithRealDb(); + Db.Insert(fakeSeries); @@ -199,7 +200,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests var fakeSeries = Builder.CreateNew().With(c => c.Id = seriesId).Build(); - WithRealDb(); + Db.Insert(fakeSeries); @@ -240,7 +241,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests var fakeSeries = Builder.CreateNew().With(c => c.Id = seriesId).Build(); - WithRealDb(); + Db.Insert(fakeSeries); Db.Insert(fakeEpisode); @@ -277,7 +278,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests var fakeSeries = Builder.CreateNew().With(c => c.Id = seriesId).Build(); - WithRealDb(); + Db.Insert(fakeSeries); @@ -316,7 +317,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests var fakeSeries = Builder.CreateNew().With(c => c.Id = seriesId).Build(); - WithRealDb(); + Db.Insert(fakeSeries); @@ -354,7 +355,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests var fakeSeries = Builder.CreateNew().With(c => c.Id = seriesId).Build(); - WithRealDb(); + Db.Insert(fakeSeries); @@ -387,7 +388,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests var fakeSeries = Builder.CreateNew().With(c => c.Id = seriesId).Build(); - WithRealDb(); + Db.Insert(fakeSeries); @@ -420,7 +421,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests var fakeSeries = Builder.CreateNew().With(c => c.Id = seriesId).Build(); - WithRealDb(); + Db.Insert(fakeSeries); @@ -455,7 +456,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests var fakeSeries = Builder.CreateNew().With(c => c.Id = seriesId).Build(); - WithRealDb(); + Db.Insert(fakeSeries); @@ -787,7 +788,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests var fakeSeries = Builder.CreateNew().With(c => c.Id = seriesId).Build(); - WithRealDb(); + Db.Insert(fakeSeries); Db.Insert(fakeEpisode); @@ -814,7 +815,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Explicit] public void Add_daily_show_episodes() { - WithRealDb(); + Mocker.Resolve(); Mocker.GetMock() @@ -843,7 +844,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void GetEpisode_by_Season_Episode_none_existing() { - WithRealDb(); + //Act var episode = Mocker.Resolve().GetEpisode(1, 1, 1); @@ -855,7 +856,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void GetEpisode_by_Season_Episode_with_EpisodeFile() { - WithRealDb(); + var fakeSeries = Builder.CreateNew().Build(); var fakeFile = Builder.CreateNew().With(f => f.Id).With(c => c.Quality = Quality.SDTV).Build(); @@ -878,7 +879,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void GetEpisode_by_Season_Episode_without_EpisodeFile() { - WithRealDb(); + var fakeSeries = Builder.CreateNew().Build(); var fakeEpisodes = Builder.CreateListOfSize(5) @@ -899,7 +900,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void GetEpisode_by_AirDate_with_EpisodeFile() { - WithRealDb(); + var fakeSeries = Builder.CreateNew().Build(); var fakeFile = Builder.CreateNew().With(f => f.Id).With(c => c.Quality = Quality.SDTV).Build(); @@ -922,7 +923,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void GetEpisode_by_AirDate_without_EpisodeFile() { - WithRealDb(); + var fakeSeries = Builder.CreateNew().Build(); var fakeEpisodes = Builder.CreateListOfSize(5) @@ -959,7 +960,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void AddEpisode_episode_is_ignored_when_full_season_is_ignored() { - WithRealDb(); + var episodes = Builder.CreateListOfSize(4) .All() @@ -997,7 +998,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void AddEpisode_episode_is_not_ignored_when_full_season_is_not_ignored() { - WithRealDb(); + var episodes = Builder.CreateListOfSize(4) .All() @@ -1031,7 +1032,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void AddEpisode_episode_is_not_ignored_when_not_full_season_is_not_ignored() { - WithRealDb(); + var episodes = Builder.CreateListOfSize(4) .All() @@ -1067,7 +1068,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void IgnoreEpisode_Ignore() { - WithRealDb(); + var episodes = Builder.CreateListOfSize(4) .All() @@ -1093,7 +1094,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void IgnoreEpisode_RemoveIgnore() { - WithRealDb(); + var episodes = Builder.CreateListOfSize(4) .All() @@ -1119,7 +1120,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void EpisodesWithoutFiles_no_specials() { - WithRealDb(); + var series = Builder.CreateNew() .With(s => s.Id = 10) @@ -1162,7 +1163,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void EpisodesWithoutFiles_with_specials() { - WithRealDb(); + var series = Builder.CreateNew() .With(s => s.Id = 10) @@ -1206,7 +1207,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void EpisodesWithFiles_success() { - WithRealDb(); + var series = Builder.CreateNew() .With(s => s.Id = 10) @@ -1250,7 +1251,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void EpisodesWithFiles_no_files() { - WithRealDb(); + var series = Builder.CreateNew() .With(s => s.Id = 10) @@ -1279,7 +1280,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void GetEpisodesByFileId_multi_episodes() { - WithRealDb(); + var series = Builder.CreateNew() .With(s => s.Id = 10) @@ -1306,7 +1307,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void GetEpisodesByFileId_single_episode() { - WithRealDb(); + var series = Builder.CreateNew() .With(s => s.Id = 10) @@ -1333,7 +1334,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void IsFirstOrLastEpisodeInSeason_false() { - WithRealDb(); + var fakeEpisodes = Builder.CreateListOfSize(10) .All() @@ -1353,7 +1354,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void IsFirstOrLastEpisodeInSeason_true_first() { - WithRealDb(); + var fakeEpisodes = Builder.CreateListOfSize(10) .All() @@ -1373,7 +1374,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void IsFirstOrLastEpisodeInSeason_true_last() { - WithRealDb(); + var fakeEpisodes = Builder.CreateListOfSize(10) .All() @@ -1398,7 +1399,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [TestCase("The Office (US) - Season 01 - Episode Title", PostDownloadStatusType.Failed, 10)] public void SetPostDownloadStatus(string folderName, PostDownloadStatusType postDownloadStatus, int episodeCount) { - WithRealDb(); + var fakeSeries = Builder.CreateNew() .With(s => s.Id = 12345) @@ -1428,7 +1429,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [Test] public void SetPostDownloadStatus_Invalid_EpisodeId() { - WithRealDb(); + var postDownloadStatus = PostDownloadStatusType.Failed; @@ -1492,7 +1493,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests var fakeSeries = Builder.CreateNew().With(c => c.Id = seriesId).Build(); - WithRealDb(); + Db.Insert(fakeSeries); @@ -1513,3 +1514,4 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests } } +*/ diff --git a/NzbDrone.Core.Test/TvTests/EpisodeProviderTests/EpisodeProviderTest_GetEpisodesByParseResult.cs b/NzbDrone.Core.Test/TvTests/EpisodeProviderTests/EpisodeProviderTest_GetEpisodesByParseResult.cs index c35c96f4c..f2749a215 100644 --- a/NzbDrone.Core.Test/TvTests/EpisodeProviderTests/EpisodeProviderTest_GetEpisodesByParseResult.cs +++ b/NzbDrone.Core.Test/TvTests/EpisodeProviderTests/EpisodeProviderTest_GetEpisodesByParseResult.cs @@ -1,4 +1,5 @@ -// ReSharper disable RedundantUsingDirective +/* +// ReSharper disable RedundantUsingDirective using System; using System.Collections.Generic; @@ -15,7 +16,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests { [TestFixture] // ReSharper disable InconsistentNaming - public class EpisodeProviderTest_GetEpisodesByParseResult : SqlCeTest + public class EpisodeProviderTest_GetEpisodesByParseResult : ObjectDbTest { private IEpisodeService episodeService; @@ -53,7 +54,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests .With(e => e.Title = "Daily Episode 1") .Build(); - WithRealDb(); + episodeService = Mocker.Resolve(); } @@ -76,7 +77,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests ep.Should().HaveCount(1); parseResult.EpisodeTitle.Should().Be(fakeEpisode.Title); VerifyEpisode(ep[0], fakeEpisode); - Db.Fetch().Should().HaveCount(1); + Db().Should().HaveCount(1); } [Test] @@ -273,3 +274,4 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests } } } +*/ diff --git a/NzbDrone.Core.Test/TvTests/EpisodeProviderTests/GetEpisodeBySceneNumberFixture.cs b/NzbDrone.Core.Test/TvTests/EpisodeProviderTests/GetEpisodeBySceneNumberFixture.cs index 366d4b560..733c934cc 100644 --- a/NzbDrone.Core.Test/TvTests/EpisodeProviderTests/GetEpisodeBySceneNumberFixture.cs +++ b/NzbDrone.Core.Test/TvTests/EpisodeProviderTests/GetEpisodeBySceneNumberFixture.cs @@ -11,7 +11,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests { [TestFixture] // ReSharper disable InconsistentNaming - public class GetEpisodeBySceneNumberFixture : SqlCeTest + public class GetEpisodeBySceneNumberFixture : ObjectDbTest { private Series _series; private Episode _episode; @@ -19,7 +19,7 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests [SetUp] public void Setup() { - WithRealDb(); + _series = Builder .CreateNew() @@ -36,7 +36,6 @@ namespace NzbDrone.Core.Test.TvTests.EpisodeProviderTests .Build(); Db.Insert(_episode); - Db.Execute("UPDATE Episodes SET SceneSeasonNumber = NULL, SceneEpisodeNumber = NULL"); } public void WithSceneNumbering() diff --git a/NzbDrone.Core.Test/TvTests/SeasonProviderTest.cs b/NzbDrone.Core.Test/TvTests/SeasonProviderTest.cs index bba507219..f5bf689e3 100644 --- a/NzbDrone.Core.Test/TvTests/SeasonProviderTest.cs +++ b/NzbDrone.Core.Test/TvTests/SeasonProviderTest.cs @@ -13,46 +13,15 @@ namespace NzbDrone.Core.Test.TvTests { [TestFixture] // ReSharper disable InconsistentNaming - public class SeasonProviderTest : SqlCeTest + public class SeasonProviderTest : ObjectDbTest { [SetUp] public void Setup() { - WithRealDb(); + } - [TestCase(true)] - [TestCase(false)] - public void SetIgnore_should_update_ignored_status(bool ignoreFlag) - { - var fakeSeason = Builder.CreateNew() - .With(s => s.Ignored = !ignoreFlag) - .Build(); - - var fakeEpisodes = Builder.CreateListOfSize(4) - .All() - .With(c => c.SeriesId = fakeSeason.SeriesId) - .With(c => c.SeasonNumber = fakeSeason.Id) - .With(c => c.Ignored = !ignoreFlag) - .Build().ToList(); - - fakeEpisodes.ForEach(c => Db.Insert(c)); - - var id = Db.Insert(fakeSeason); - - //Act - Mocker.Resolve().SetIgnore(fakeSeason.SeriesId, fakeSeason.SeasonNumber, ignoreFlag); - - //Assert - var season = Db.SingleOrDefault(id); - season.Ignored.Should().Be(ignoreFlag); - - var episodes = Db.Fetch(); - episodes.Should().HaveSameCount(fakeEpisodes); - episodes.Should().OnlyContain(c => c.Ignored == ignoreFlag); - } - [TestCase(true)] [TestCase(false)] public void IsIgnored_should_return_ignored_status_of_season(bool ignoreFlag) @@ -111,7 +80,7 @@ namespace NzbDrone.Core.Test.TvTests const int seriesId = 10; //Setup - WithRealDb(); + var seasons = Builder.CreateListOfSize(5) .All() diff --git a/NzbDrone.Core/App.config b/NzbDrone.Core/App.config index fc91a3745..99ddf3e08 100644 --- a/NzbDrone.Core/App.config +++ b/NzbDrone.Core/App.config @@ -1,13 +1,3 @@  - -
- - - - - - - - \ No newline at end of file diff --git a/NzbDrone.Core/ContainerExtentions.cs b/NzbDrone.Core/ContainerExtentions.cs index 80b8f7058..a31effc8c 100644 --- a/NzbDrone.Core/ContainerExtentions.cs +++ b/NzbDrone.Core/ContainerExtentions.cs @@ -11,7 +11,6 @@ using NzbDrone.Core.Indexers; using NzbDrone.Core.Instrumentation; using NzbDrone.Core.Providers.Metadata; using NzbDrone.Core.Providers.Search; -using PetaPoco; namespace NzbDrone.Core { @@ -62,15 +61,7 @@ namespace NzbDrone.Core var appDataPath = new EnvironmentProvider().GetAppDataPath(); if (!Directory.Exists(appDataPath)) Directory.CreateDirectory(appDataPath); - container.Register(c => c.Resolve().GetMainPetaPocoDb()) - .As(); - container.Register(c => c.Resolve().GetLogPetaPocoDb(false)) - .SingleInstance() - .Named("DatabaseTarget"); - - container.Register(c => c.Resolve().GetLogPetaPocoDb()) - .Named("LogProvider"); container.Register(c => { @@ -78,9 +69,6 @@ namespace NzbDrone.Core }).As().SingleInstance(); container.RegisterGeneric(typeof(BasicRepository<>)).As(typeof(IBasicRepository<>)); - - container.RegisterType().WithParameter(ResolvedParameter.ForNamed("DatabaseTarget")); - container.RegisterType().WithParameter(ResolvedParameter.ForNamed("LogProvider")); } } } \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/BasicRepository.cs b/NzbDrone.Core/Datastore/BasicRepository.cs index 0ae110aa9..000f5627b 100644 --- a/NzbDrone.Core/Datastore/BasicRepository.cs +++ b/NzbDrone.Core/Datastore/BasicRepository.cs @@ -3,7 +3,7 @@ using System.Linq; namespace NzbDrone.Core.Datastore { - public interface IBasicRepository + public interface IBasicRepository where TModel : ModelBase, new() { IEnumerable All(); int Count(); @@ -15,6 +15,7 @@ namespace NzbDrone.Core.Datastore IList InsertMany(IList model); IList UpdateMany(IList model); void Purge(); + bool HasItems(); } public class BasicRepository : IBasicRepository where TModel : ModelBase, new() @@ -90,5 +91,10 @@ namespace NzbDrone.Core.Datastore { DeleteMany(Queryable.Select(c => c.Id)); } + + public bool HasItems() + { + return Queryable.Any(); + } } } diff --git a/NzbDrone.Core/Datastore/ConnectionFactory.cs b/NzbDrone.Core/Datastore/ConnectionFactory.cs deleted file mode 100644 index 3cf62665c..000000000 --- a/NzbDrone.Core/Datastore/ConnectionFactory.cs +++ /dev/null @@ -1,160 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Data; -using System.Data.Common; -using System.Reflection; -using NLog; -using NzbDrone.Common; -using PetaPoco; - -namespace NzbDrone.Core.Datastore -{ - public class ConnectionFactory - { - private readonly EnvironmentProvider _environmentProvider; - private static readonly Logger logger = LogManager.GetLogger("ConnectionFactory"); - private static readonly DbProviderFactory _factory; - - static ConnectionFactory() - { - Database.Mapper = new CustomeMapper(); - - if (EnvironmentProvider.IsMono) return; - - var dataSet = (DataSet)ConfigurationManager.GetSection("system.data"); - dataSet.Tables[0].Rows.Add("Microsoft SQL Server Compact Data Provider 4.0" - , "System.Data.SqlServerCe.4.0" - , ".NET Framework Data Provider for Microsoft SQL Server Compact" - , - "System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"); - - _factory = SqlCeProxy.GetSqlCeProviderFactory(); - } - - - public ConnectionFactory(EnvironmentProvider environmentProvider) - { - _environmentProvider = environmentProvider; - } - - public String MainConnectionString - { - get - { - return GetConnectionString(_environmentProvider.GetSqlCeMainDbPath()); - } - } - - public String LogConnectionString - { - get - { - return GetConnectionString(_environmentProvider.GetSqlCeLogDbPath()); - } - } - - public static string GetConnectionString(string path) - { - return String.Format("Data Source=\"{0}\"; Max Database Size = 512;", path); - } - - public IDatabase GetMainPetaPocoDb(Boolean profiled = true) - { - return GetPetaPocoDb(MainConnectionString, profiled); - } - - public IDatabase GetLogPetaPocoDb(Boolean profiled = true) - { - return GetPetaPocoDb(LogConnectionString, profiled); - } - - - static readonly HashSet initilized = new HashSet(); - - - - public static IDatabase GetPetaPocoDb(string connectionString, Boolean profiled = true) - { - if (EnvironmentProvider.IsMono) - { - throw new NotSupportedException("SqlCe is not supported in mono"); - } - - lock (initilized) - { - if (!initilized.Contains(connectionString)) - { - //VerifyDatabase(connectionString); - MigrationsHelper.Run(connectionString, true); - initilized.Add(connectionString); - } - } - - - - var db = new Database(connectionString, _factory, Database.DBType.SqlServerCE) - { - KeepConnectionAlive = true, - ForceDateTimesToUtc = false, - }; - - return db; - } - - /*private static void VerifyDatabase(string connectionString) - { - logger.Debug("Verifying database {0}", connectionString); - - var sqlConnection = new SqlCeConnection(connectionString); - - if (!File.Exists(sqlConnection.Database)) - { - logger.Debug("database file doesn't exist. {0}", sqlConnection.Database); - return; - } - - using (var sqlEngine = new SqlCeEngine(connectionString)) - { - - if (sqlEngine.Verify(VerifyOption.Default)) - { - logger.Debug("Database integrity verified."); - } - else - { - logger.Error("Database verification failed."); - RepairDatabase(connectionString); - } - } - } - - private static void RepairDatabase(string connectionString) - { - logger.Info("Attempting to repair database: {0}", connectionString); - using (var sqlEngine = new SqlCeEngine(connectionString)) - { - try - { - sqlEngine.Repair(connectionString, RepairOption.RecoverAllOrFail); - logger.Info("Recovery was successful without any data loss {0}", connectionString); - } - catch (SqlCeException e) - { - if (e.Message.Contains("file sharing violation")) - { - logger.WarnException("file is in use. skipping.", e); - return; - } - logger.WarnException( - "Safe recovery failed. will attempts a more aggressive strategy. might cause loss of data.", - e); - sqlEngine.Repair(connectionString, RepairOption.DeleteCorruptedRows); - logger.Warn("Database was recovered. some data might have been lost"); - - //TODO: do db cleanup to avoid broken relationships. - } - } - }*/ - } -} diff --git a/NzbDrone.Core/Datastore/CustomeMapper.cs b/NzbDrone.Core/Datastore/CustomeMapper.cs deleted file mode 100644 index 87219400f..000000000 --- a/NzbDrone.Core/Datastore/CustomeMapper.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System; -using System.Reflection; -using NzbDrone.Core.Qualities; -using PetaPoco; - -namespace NzbDrone.Core.Datastore -{ - public class CustomeMapper : DefaultMapper - { - public override Func GetToDbConverter(Type sourceType) - { - if (sourceType == typeof(Quality)) - { - return delegate(object s) - { - var source = (Quality)s; - return source.Id; - }; - } - - return base.GetToDbConverter(sourceType); - } - - public override Func GetFromDbConverter(Type destinationType, Type sourceType) - { - if ((sourceType == typeof(Int32) || sourceType == typeof(Int64)) && destinationType.IsGenericType && destinationType.GetGenericTypeDefinition() == typeof(Nullable<>)) - { - // If it is NULLABLE, then get the underlying type. eg if "Nullable" then this will return just "int" - Type genericArgument = destinationType.GetGenericArguments()[0]; - if (genericArgument == typeof(DayOfWeek)) - { - return delegate(object s) - { - int value; - Int32.TryParse(s.ToString(), out value); - return (DayOfWeek?)value; - }; - } - - return delegate(object s) - { - int value; - Int32.TryParse(s.ToString(), out value); - return value; - }; - } - - if ((sourceType == typeof(Int32) || sourceType == typeof(Int64)) && destinationType == typeof(Quality)) - { - return delegate(object s) - { - int value; - Int32.TryParse(s.ToString(), out value); - var quality = (Quality)value; - return quality; - }; - } - - return base.GetFromDbConverter(destinationType, sourceType); - } - - public override Func GetFromDbConverter(PropertyInfo propertyInfo, Type sourceType) - { - //Only needed if using dynamic as the return type from DB, not implemented currently as it has no use right now - //if (propertyInfo == null) - // return null; - - if (propertyInfo == null) return base.GetFromDbConverter(propertyInfo, sourceType); - - return GetFromDbConverter(propertyInfo.PropertyType, sourceType); - } - } - - -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/MigrationLogger.cs b/NzbDrone.Core/Datastore/MigrationLogger.cs deleted file mode 100644 index 46de8a280..000000000 --- a/NzbDrone.Core/Datastore/MigrationLogger.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System; -using System.Collections.Generic; -using Migrator.Framework; -using NLog; - -namespace NzbDrone.Core.Datastore -{ - public class MigrationLogger : ILogger - { - - private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - - public void Started(List currentVersion, long finalVersion) - { - Logger.Debug("Starting database migration {0} -> {1}", String.Join(",", currentVersion), finalVersion); - } - - public void MigrateUp(long version, string migrationName) - { - Logger.Info("Starting migration {0} [{1}]", version, migrationName); - } - - public void MigrateDown(long version, string migrationName) - { - Logger.Info("Starting MigrateDown {0} [{1}]", version, migrationName); - } - - public void Skipping(long version) - { - Logger.Info("Skipping MigrateDown {0}", version); - } - - public void RollingBack(long originalVersion) - { - Logger.Info("Rolling Back to {0}", originalVersion); - } - - public void ApplyingDBChange(string sql) - { - Logger.Info("Applying DB Change {0}", sql); - } - - public void Exception(long version, string migrationName, Exception ex) - { - Logger.ErrorException(migrationName + " " + version, ex); - } - - public void Exception(string message, Exception ex) - { - Logger.ErrorException(message, ex); - } - - public void Finished(List currentVersion, long finalVersion) - { - Logger.Info("Finished Datastore migration {0} -> {1}", String.Join(",", currentVersion), finalVersion); - } - - public void Log(string format, params object[] args) - { - Logger.Info(format, args); - } - - public void Warn(string format, params object[] args) - { - Logger.Warn(format, args); - } - - public void Trace(string format, params object[] args) - { - //Logger.Trace(format, args); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20110707.cs b/NzbDrone.Core/Datastore/Migrations/Migration20110707.cs deleted file mode 100644 index 68dfc59c7..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20110707.cs +++ /dev/null @@ -1,167 +0,0 @@ -using System; -using System.Data; -using Migrator.Framework; -using NzbDrone.Common; - -namespace NzbDrone.Core.Datastore.Migrations -{ - - [Migration(20110707)] - public class Migration20110707 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.AddTable("Series", new[] - { - new Column("SeriesId", DbType.Int32, ColumnProperty.PrimaryKey), - new Column("Title", DbType.String, ColumnProperty.Null), - new Column("CleanTitle", DbType.String, ColumnProperty.Null), - new Column("Status", DbType.String, ColumnProperty.Null), - new Column("Overview", DbType.String,4000, ColumnProperty.Null), - new Column("AirsDayOfWeek", DbType.Int32, ColumnProperty.Null), - new Column("AirTimes", DbType.String, ColumnProperty.Null), - new Column("Language", DbType.String, ColumnProperty.Null), - new Column("Path", DbType.String,4000, ColumnProperty.NotNull), - new Column("Monitored", DbType.Boolean, ColumnProperty.NotNull), - new Column("QualityProfileId", DbType.Int32, ColumnProperty.NotNull), - new Column("SeasonFolder", DbType.Boolean, ColumnProperty.NotNull), - new Column("LastInfoSync", DbType.DateTime, ColumnProperty.Null), - new Column("LastDiskSync", DbType.DateTime, ColumnProperty.Null) - }); - - Database.AddTable("Episodes", new[] - { - new Column("EpisodeId", DbType.Int32, ColumnProperty.PrimaryKeyWithIdentity), - new Column("TvDbEpisodeId", DbType.Int32, ColumnProperty.Null), - new Column("SeriesId", DbType.Int32, ColumnProperty.NotNull), - new Column("SeasonNumber", DbType.Int32, ColumnProperty.NotNull), - new Column("EpisodeNumber", DbType.Int32, ColumnProperty.NotNull), - new Column("Title", DbType.String,100, ColumnProperty.Null), - new Column("Overview", DbType.String,4000, ColumnProperty.Null), - new Column("Ignored", DbType.Boolean, ColumnProperty.NotNull), - new Column("EpisodeFileId", DbType.Int32, ColumnProperty.Null), - new Column("AirDate", DbType.DateTime, ColumnProperty.Null), - new Column("GrabDate", DbType.DateTime, ColumnProperty.Null) - }); - - var indexName = MigrationsHelper.GetIndexName("Episodes", "SeriesId"); - Database.AddIndex(indexName, "Episodes", "SeriesId"); - - indexName = MigrationsHelper.GetIndexName("Episodes", "EpisodeFileId"); - Database.AddIndex(indexName, "Episodes", "EpisodeFileId"); - - indexName = MigrationsHelper.GetIndexName("Episodes", "AirDate"); - Database.AddIndex(indexName, "Episodes", "AirDate"); - - indexName = MigrationsHelper.GetIndexName("Episodes", "TvDbEpisodeId"); - Database.AddIndex(indexName, "Episodes", "TvDbEpisodeId"); - - - Database.AddTable("EpisodeFiles", new[] - { - new Column("EpisodeFileId", DbType.Int32, - ColumnProperty.PrimaryKeyWithIdentity), - new Column("SeriesId", DbType.Int32, ColumnProperty.NotNull), - new Column("Path", DbType.String,4000, ColumnProperty.NotNull), - new Column("Quality", DbType.Int32, ColumnProperty.NotNull), - new Column("Proper", DbType.Int32, ColumnProperty.NotNull), - new Column("Size", DbType.Int64, ColumnProperty.NotNull), - new Column("DateAdded", DbType.DateTime, ColumnProperty.NotNull), - new Column("SeasonNumber", DbType.Int32, ColumnProperty.NotNull) - }); - - indexName = MigrationsHelper.GetIndexName("EpisodeFiles", "SeriesId"); - Database.AddIndex(indexName, "Episodes", "SeriesId"); - - - Database.AddTable("Config", new[] - { - new Column("Key", DbType.String, ColumnProperty.PrimaryKey), - new Column("Value", DbType.String, ColumnProperty.NotNull) - }); - - Database.AddTable("SceneMappings", new[] - { - new Column("CleanTitle", DbType.String, ColumnProperty.PrimaryKey), - new Column("SeriesId", DbType.Int32, ColumnProperty.NotNull), - new Column("SceneName", DbType.String, ColumnProperty.NotNull) - }); - - Database.AddTable("History", new[] - { - new Column("HistoryId", DbType.Int64, ColumnProperty.PrimaryKeyWithIdentity), - new Column("EpisodeId", DbType.Int32, ColumnProperty.NotNull), - new Column("SeriesId", DbType.Int32, ColumnProperty.NotNull), - new Column("NzbTitle", DbType.String, ColumnProperty.NotNull), - new Column("Date", DbType.DateTime, ColumnProperty.NotNull), - new Column("Quality", DbType.Int32, ColumnProperty.NotNull), - new Column("IsProper", DbType.Boolean, ColumnProperty.NotNull), - new Column("Indexer", DbType.String, ColumnProperty.NotNull) - }); - - indexName = MigrationsHelper.GetIndexName("History", "EpisodeId"); - Database.AddIndex(indexName, "History", "EpisodeId"); - - indexName = MigrationsHelper.GetIndexName("History", "SeriesId"); - Database.AddIndex(indexName, "History", "SeriesId"); - - Database.AddTable("RootDirs", new[] - { - new Column("Id", DbType.Int32, ColumnProperty.PrimaryKeyWithIdentity), - new Column("Path", DbType.String, 4000, ColumnProperty.NotNull) - }); - - Database.AddTable("ExternalNotificationSettings", new[] - { - new Column("Id", DbType.Int32, ColumnProperty.PrimaryKeyWithIdentity), - new Column("Enabled", DbType.Boolean, ColumnProperty.NotNull), - new Column("NotifierName", DbType.String, ColumnProperty.NotNull), - new Column("Name", DbType.String, ColumnProperty.NotNull) - }); - - Database.AddTable("JobDefinitions", new[] - { - new Column("Id", DbType.Int32, ColumnProperty.PrimaryKeyWithIdentity), - new Column("Enable", DbType.Boolean, ColumnProperty.NotNull), - new Column("TypeName", DbType.String, ColumnProperty.NotNull), - new Column("Name", DbType.String, ColumnProperty.NotNull), - new Column("Interval", DbType.Int32, ColumnProperty.NotNull), - new Column("LastExecution", DbType.DateTime, ColumnProperty.NotNull), - new Column("Success", DbType.Boolean, ColumnProperty.NotNull) - }); - - Database.AddTable("QualityProfiles", new[] - { - new Column("QualityProfileId", DbType.Int32, ColumnProperty.PrimaryKeyWithIdentity), - new Column("Name", DbType.String, ColumnProperty.NotNull), - new Column("Cutoff", DbType.Int32, ColumnProperty.NotNull), - new Column("SonicAllowed", DbType.String, ColumnProperty.NotNull), - }); - - Database.AddTable("IndexerDefinitions", new[] - { - new Column("Id", DbType.Int32, ColumnProperty.PrimaryKeyWithIdentity), - new Column("Enable", DbType.Boolean, ColumnProperty.NotNull), - new Column("IndexProviderType", DbType.String, ColumnProperty.NotNull), - new Column("Name", DbType.String, ColumnProperty.NotNull), - }); - } - - - protected override void LogDbUpgrade() - { - - Database.AddTable("Logs", new[] - { - new Column("LogId", DbType.Int64, ColumnProperty.PrimaryKeyWithIdentity), - new Column("Message", DbType.String,4000, ColumnProperty.NotNull), - new Column("Time", DbType.DateTime, ColumnProperty.NotNull), - new Column("Logger", DbType.String, ColumnProperty.NotNull), - new Column("Method", DbType.String, ColumnProperty.NotNull), - new Column("Exception", DbType.String,4000, ColumnProperty.Null), - new Column("ExceptionType", DbType.String, ColumnProperty.Null), - new Column("Level", DbType.String, ColumnProperty.NotNull) - }); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20110726.cs b/NzbDrone.Core/Datastore/Migrations/Migration20110726.cs deleted file mode 100644 index e064ca101..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20110726.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using System.Data; -using Migrator.Framework; - -namespace NzbDrone.Core.Datastore.Migrations -{ - - [Migration(20110726)] - public class Migration20110726 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.RemoveTable("ExternalNotificationSettings"); - - Database.AddTable("ExternalNotificationDefinitions", new[] - { - new Column("Id", DbType.Int32, ColumnProperty.PrimaryKeyWithIdentity), - new Column("Enable", DbType.Boolean, ColumnProperty.NotNull), - new Column("ExternalNotificationProviderType", DbType.String, ColumnProperty.NotNull), - new Column("Name", DbType.String, ColumnProperty.NotNull) - }); - } - - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20110909.cs b/NzbDrone.Core/Datastore/Migrations/Migration20110909.cs deleted file mode 100644 index 1c041f13f..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20110909.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using System.Data; -using Migrator.Framework; - -namespace NzbDrone.Core.Datastore.Migrations -{ - - [Migration(20110909)] - public class Migration20110909 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.AddColumn("Series", "Runtime", DbType.Int32, ColumnProperty.Null); - Database.AddColumn("Series", "BannerUrl", DbType.String, ColumnProperty.Null); - - Database.AddTable("QualityTypes", new[] - { - new Column("QualityTypeId", DbType.Int32, ColumnProperty.PrimaryKey), - new Column("Name", DbType.String, ColumnProperty.NotNull), - new Column("MinSize", DbType.Int32, ColumnProperty.NotNull), - new Column("MaxSize", DbType.Int32, ColumnProperty.NotNull) - }); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20111011.cs b/NzbDrone.Core/Datastore/Migrations/Migration20111011.cs deleted file mode 100644 index 68f642e3e..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20111011.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Data; -using Migrator.Framework; - -namespace NzbDrone.Core.Datastore.Migrations -{ - - [Migration(20111011)] - public class Migration20111011 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.AddColumn("Episodes", "PostDownloadStatus", DbType.Int32, ColumnProperty.Null); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20111112.cs b/NzbDrone.Core/Datastore/Migrations/Migration20111112.cs deleted file mode 100644 index ad0db8728..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20111112.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Data; -using Migrator.Framework; - -namespace NzbDrone.Core.Datastore.Migrations -{ - - [Migration(20111112)] - public class Migration2011112 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.AddTable("NewznabDefinitions", new[] - { - new Column("Id", DbType.Int32, ColumnProperty.PrimaryKeyWithIdentity), - new Column("Enable", DbType.Boolean, ColumnProperty.NotNull), - new Column("Name", DbType.String, ColumnProperty.Null), - new Column("Url", DbType.String, ColumnProperty.Null), - new Column("ApiKey", DbType.String, ColumnProperty.Null) - }); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20111125.cs b/NzbDrone.Core/Datastore/Migrations/Migration20111125.cs deleted file mode 100644 index aa3aaf20d..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20111125.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Data; -using Migrator.Framework; - -namespace NzbDrone.Core.Datastore.Migrations -{ - - [Migration(20111125)] - public class Migration2011125 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.AddColumn("Series", "IsDaily", DbType.Boolean, ColumnProperty.Null); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20120118.cs b/NzbDrone.Core/Datastore/Migrations/Migration20120118.cs deleted file mode 100644 index 627310419..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20120118.cs +++ /dev/null @@ -1,14 +0,0 @@ -using Migrator.Framework; - -namespace NzbDrone.Core.Datastore.Migrations -{ - - [Migration(20120118)] - public class Migration20120118 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.ExecuteNonQuery("DELETE FROM SERIES WHERE SeriesID = 0"); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20120123.cs b/NzbDrone.Core/Datastore/Migrations/Migration20120123.cs deleted file mode 100644 index 13cf157ed..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20120123.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Data; -using Migrator.Framework; - -namespace NzbDrone.Core.Datastore.Migrations -{ - [Migration(20120123)] - public class Migration20120123 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.AddColumn("Series", "BacklogSetting", DbType.Int32, ColumnProperty.Null); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20120220.cs b/NzbDrone.Core/Datastore/Migrations/Migration20120220.cs deleted file mode 100644 index b9e4d291d..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20120220.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Data; -using Migrator.Framework; - -namespace NzbDrone.Core.Datastore.Migrations -{ - - [Migration(20120220)] - public class Migration20120220 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.AddTable("Seasons", new[] - { - new Column("SeasonId", DbType.Int32, ColumnProperty.PrimaryKeyWithIdentity), - new Column("SeriesId", DbType.Int32, ColumnProperty.NotNull), - new Column("SeasonNumber", DbType.Int32, ColumnProperty.NotNull), - new Column("Ignored", DbType.Boolean, ColumnProperty.NotNull) - }); - - Database.ExecuteNonQuery(@"INSERT INTO Seasons (SeriesId, SeasonNumber, Ignored) - SELECT SeriesId, SeasonNumber, - CASE WHEN Count(*) = - SUM(CASE WHEN Ignored = 1 THEN 1 ELSE 0 END) THEN 1 ELSE 0 END AS Ignored - FROM Episodes - GROUP BY SeriesId, SeasonNumber"); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20120227.cs b/NzbDrone.Core/Datastore/Migrations/Migration20120227.cs deleted file mode 100644 index 016bf41d4..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20120227.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Migrator.Framework; - -namespace NzbDrone.Core.Datastore.Migrations -{ - - [Migration(20120227)] - public class Migration20120227 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.ExecuteNonQuery(@"DELETE FROM Seasons WHERE SeasonNumber NOT IN - ( - SELECT DISTINCT SeasonNumber - FROM Episodes - WHERE Seasons.SeriesId = Episodes.SeriesId - )"); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20120228.cs b/NzbDrone.Core/Datastore/Migrations/Migration20120228.cs deleted file mode 100644 index c707e2671..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20120228.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Data; -using Migrator.Framework; - -namespace NzbDrone.Core.Datastore.Migrations -{ - - [Migration(20120228)] - public class Migration20120228 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.AddColumn("Series", "Network", DbType.String, ColumnProperty.Null); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20120420.cs b/NzbDrone.Core/Datastore/Migrations/Migration20120420.cs deleted file mode 100644 index 839d416f0..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20120420.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Data; -using Migrator.Framework; - -namespace NzbDrone.Core.Datastore.Migrations -{ - [Migration(20120420)] - public class Migration20120420 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.AddTable("SearchHistory", new[] - { - new Column("Id", DbType.Int32, ColumnProperty.PrimaryKeyWithIdentity), - new Column("SeriesId", DbType.Int32, ColumnProperty.NotNull), - new Column("SeasonNumber", DbType.Int32, ColumnProperty.Null), - new Column("EpisodeId", DbType.Int32, ColumnProperty.Null), - new Column("SearchTime", DbType.DateTime, ColumnProperty.NotNull), - new Column("SuccessfulDownload", DbType.Boolean, ColumnProperty.NotNull) - }); - - Database.AddTable("SearchHistoryItems", new[] - { - new Column("Id", DbType.Int32, ColumnProperty.PrimaryKeyWithIdentity), - new Column("SearchHistoryId", DbType.Int32, ColumnProperty.NotNull), - new Column("ReportTitle", DbType.String, ColumnProperty.NotNull), - new Column("Indexer", DbType.String, ColumnProperty.NotNull), - new Column("NzbUrl", DbType.String, ColumnProperty.NotNull), - new Column("NzbInfoUrl", DbType.String, ColumnProperty.Null), - new Column("Success", DbType.Boolean, ColumnProperty.NotNull), - new Column("SearchError", DbType.Int32, ColumnProperty.NotNull), - new Column("Quality", DbType.Int32, ColumnProperty.NotNull), - new Column("Proper", DbType.Boolean, ColumnProperty.NotNull), - new Column("Age", DbType.Int32, ColumnProperty.NotNull), - new Column("Language", DbType.Int32, ColumnProperty.NotNull), - new Column("Size", DbType.Int64, ColumnProperty.NotNull), - }); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20120430.cs b/NzbDrone.Core/Datastore/Migrations/Migration20120430.cs deleted file mode 100644 index ca949c36b..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20120430.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Data; -using Migrator.Framework; - -namespace NzbDrone.Core.Datastore.Migrations -{ - - [Migration(20120430)] - public class Migration20120430 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.AddColumn("History", "NzbInfoUrl", DbType.String, ColumnProperty.Null); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20120504.cs b/NzbDrone.Core/Datastore/Migrations/Migration20120504.cs deleted file mode 100644 index 6cc851714..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20120504.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Data; -using Migrator.Framework; - -namespace NzbDrone.Core.Datastore.Migrations -{ - - [Migration(20120504)] - public class Migration20120504 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.AddColumn("NewznabDefinitions", "BuiltIn", DbType.Boolean, ColumnProperty.Null); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20120707.cs b/NzbDrone.Core/Datastore/Migrations/Migration20120707.cs deleted file mode 100644 index e93c4446d..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20120707.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Data; -using Migrator.Framework; - -namespace NzbDrone.Core.Datastore.Migrations -{ - - [Migration(20120707)] - public class Migration20120707 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.AddTable("MetadataDefinitions", new[] - { - new Column("Id", DbType.Int32, ColumnProperty.PrimaryKeyWithIdentity), - new Column("Enable", DbType.Boolean, ColumnProperty.NotNull), - new Column("MetadataProviderType", DbType.String, ColumnProperty.NotNull), - new Column("Name", DbType.String, ColumnProperty.NotNull) - }); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20120727.cs b/NzbDrone.Core/Datastore/Migrations/Migration20120727.cs deleted file mode 100644 index 44ef7d46d..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20120727.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using System.Data; -using Migrator.Framework; -using NzbDrone.Common; - -namespace NzbDrone.Core.Datastore.Migrations -{ - - [Migration(20120727)] - public class Migration20120727 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.ExecuteNonQuery(@"DELETE FROM History - WHERE HistoryId IN - ( - SELECT History.HistoryId - FROM History - LEFT OUTER JOIN Episodes - ON History.EpisodeId = Episodes.EpisodeId - WHERE Episodes.Title is null - )"); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20120802.cs b/NzbDrone.Core/Datastore/Migrations/Migration20120802.cs deleted file mode 100644 index fbe04ca84..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20120802.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Data; -using Migrator.Framework; -using NzbDrone.Common; - -namespace NzbDrone.Core.Datastore.Migrations -{ - - [Migration(20120802)] - public class Migration20120802 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.AddColumn("EpisodeFiles", new Column("SceneName", DbType.String, ColumnProperty.Null)); - Database.AddColumn("EpisodeFiles", new Column("ReleaseGroup", DbType.String, ColumnProperty.Null)); - Database.AddColumn("History", new Column("ReleaseGroup", DbType.String, ColumnProperty.Null)); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20120918.cs b/NzbDrone.Core/Datastore/Migrations/Migration20120918.cs deleted file mode 100644 index f5cf8a93e..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20120918.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Data; -using Migrator.Framework; -using NzbDrone.Common; - -namespace NzbDrone.Core.Datastore.Migrations -{ - - [Migration(20120918)] - public class Migration20120918 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.AddColumn("Series", new Column("DownloadEpisodesAiredAfter", DbType.DateTime, ColumnProperty.Null)); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20120919.cs b/NzbDrone.Core/Datastore/Migrations/Migration20120919.cs deleted file mode 100644 index 5790ef024..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20120919.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Data; -using Migrator.Framework; -using NzbDrone.Common; - -namespace NzbDrone.Core.Datastore.Migrations -{ - - [Migration(20120919)] - public class Migration20120919 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.AddColumn("Series", new Column("CustomStartDate", DbType.DateTime, ColumnProperty.Null)); - - Database.ExecuteNonQuery("UPDATE Series SET CustomStartDate = DownloadEpisodesAiredAfter"); - - Database.RemoveColumn("Series", "DownloadEpisodesAiredAfter"); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20121012.cs b/NzbDrone.Core/Datastore/Migrations/Migration20121012.cs deleted file mode 100644 index fe055f9d3..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20121012.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Data; -using Migrator.Framework; -using NzbDrone.Common; - -namespace NzbDrone.Core.Datastore.Migrations -{ - - [Migration(20121012)] - public class Migration20121012 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.AddColumn("Episodes", new Column("AbsoluteEpisodeNumber", DbType.Int32, ColumnProperty.Null)); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20121016.cs b/NzbDrone.Core/Datastore/Migrations/Migration20121016.cs deleted file mode 100644 index 0a8c55e5b..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20121016.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Data; -using Migrator.Framework; -using NzbDrone.Common; - -namespace NzbDrone.Core.Datastore.Migrations -{ - [Migration(20121016)] - public class Migration20121016 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.AddColumn("Episodes", new Column("SceneAbsoluteEpisodeNumber", DbType.Int32, ColumnProperty.Null)); - Database.AddColumn("Episodes", new Column("SceneSeasonNumber", DbType.Int32, ColumnProperty.Null)); - Database.AddColumn("Episodes", new Column("SceneEpisodeNumber", DbType.Int32, ColumnProperty.Null)); - - Database.AddColumn("Series", new Column("UseSceneNumbering", DbType.Boolean, ColumnProperty.Null)); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20121122.cs b/NzbDrone.Core/Datastore/Migrations/Migration20121122.cs deleted file mode 100644 index b81351485..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20121122.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Data; -using Migrator.Framework; -using NzbDrone.Common; - -namespace NzbDrone.Core.Datastore.Migrations -{ - [Migration(20121122)] - public class Migration20121122 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.ExecuteNonQuery("UPDATE Config SET [KEY] = 'SabBacklogTvPriority' WHERE [KEY] = 'SabTvPriority'"); - Database.ExecuteNonQuery("UPDATE Config SET [KEY] = 'DownloadClientTvDirectory' WHERE [KEY] = 'SabTvDropDirectory'"); - - var priority = Database.ExecuteScalar("SELECT [Value] FROM Config WHERE [Key] = 'SabBacklogTvPriority'"); - - if (priority != null) - Database.ExecuteNonQuery("INSERT INTO Config ([Key], [Value]) VALUES('SabRecentTvPriority', '" + priority + "')"); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20121202.cs b/NzbDrone.Core/Datastore/Migrations/Migration20121202.cs deleted file mode 100644 index 3ecf6f285..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20121202.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Data; -using Migrator.Framework; -using NzbDrone.Common; - -namespace NzbDrone.Core.Datastore.Migrations -{ - [Migration(20121202)] - public class Migration20121202 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.ExecuteNonQuery("DELETE FROM Config WHERE [KEY] = 'NewzbinUsername'"); - Database.ExecuteNonQuery("DELETE FROM Config WHERE [KEY] = 'NewzbinPassword'"); - Database.ExecuteNonQuery("DELETE FROM IndexerDefinitions WHERE IndexProviderType = 'NzbDrone.Core.Providers.Indexer.Newzbin'"); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20121209.cs b/NzbDrone.Core/Datastore/Migrations/Migration20121209.cs deleted file mode 100644 index db71af7e5..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20121209.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Data; -using Migrator.Framework; -using NzbDrone.Common; - -namespace NzbDrone.Core.Datastore.Migrations -{ - [Migration(20121209)] - public class Migration20121209 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.ExecuteNonQuery("DELETE FROM Config WHERE [KEY] = 'NzbMatrixUsername'"); - Database.ExecuteNonQuery("DELETE FROM Config WHERE [KEY] = 'NzbMatrixApiKey'"); - Database.ExecuteNonQuery("DELETE FROM IndexerDefinitions WHERE IndexProviderType = 'NzbDrone.Core.Providers.Indexer.NzbMatrix'"); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20121218.cs b/NzbDrone.Core/Datastore/Migrations/Migration20121218.cs deleted file mode 100644 index 00061a9e1..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20121218.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Data; -using Migrator.Framework; -using NzbDrone.Common; - -namespace NzbDrone.Core.Datastore.Migrations -{ - [Migration(20121218)] - public class Migration20121218 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.AddColumn("Series", new Column("TvRageId", DbType.Int32, ColumnProperty.Null)); - Database.AddColumn("Series", new Column("TvRageTitle", DbType.String, ColumnProperty.Null)); - Database.AddColumn("Series", new Column("UtcOffset", DbType.Int32, ColumnProperty.Null)); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20121223.cs b/NzbDrone.Core/Datastore/Migrations/Migration20121223.cs deleted file mode 100644 index a7a65ff6f..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20121223.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Data; -using Migrator.Framework; -using NzbDrone.Common; - -namespace NzbDrone.Core.Datastore.Migrations -{ - [Migration(20121223)] - public class Migration20121223 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.AddColumn("SceneMappings", new Column("SeasonNumber", DbType.Int32, ColumnProperty.Null)); - Database.ExecuteNonQuery("UPDATE SceneMappings SET SeasonNumber = -1 WHERE SeasonNumber IS NULL"); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20121226.cs b/NzbDrone.Core/Datastore/Migrations/Migration20121226.cs deleted file mode 100644 index fdbce1992..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20121226.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Data; -using Migrator.Framework; -using NzbDrone.Common; - -namespace NzbDrone.Core.Datastore.Migrations -{ - [Migration(20121226)] - public class Migration20121226 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - Database.AddColumn("Series", new Column("FirstAired", DbType.DateTime, ColumnProperty.Null)); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/Migration20130203.cs b/NzbDrone.Core/Datastore/Migrations/Migration20130203.cs deleted file mode 100644 index 29b15c425..000000000 --- a/NzbDrone.Core/Datastore/Migrations/Migration20130203.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Collections.Generic; -using Migrator.Framework; -using NzbDrone.Core.Repository; -using NzbDrone.Core.RootFolders; - -namespace NzbDrone.Core.Datastore.Migrations -{ - [Migration(20130203)] - public class Migration20130203 : NzbDroneMigration - { - protected override void MainDbUpgrade() - { - var objectDb = GetObjectDb(); - - using (var dataReader = Database.ExecuteQuery("SELECT * from RootDirs")) - { - var dirs = new List(); - while (dataReader.Read()) - { - var rootFolder = new RootFolder { Path = dataReader["Path"].ToString() }; - dirs.Add(rootFolder); - } - objectDb.InsertMany(dirs); - } - - //Database.RemoveTable("RootDirs"); - - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/Migrations/NzbDroneMigration.cs b/NzbDrone.Core/Datastore/Migrations/NzbDroneMigration.cs deleted file mode 100644 index 90864e9d2..000000000 --- a/NzbDrone.Core/Datastore/Migrations/NzbDroneMigration.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Reflection; -using Migrator.Framework; -using NzbDrone.Common; - -namespace NzbDrone.Core.Datastore.Migrations -{ - public abstract class NzbDroneMigration : Migration - { - protected virtual void MainDbUpgrade() - { - } - - protected virtual void LogDbUpgrade() - { - } - - public override void Up() - { - if (Database.ConnectionString.Contains(PathExtentions.NZBDRONE_SQLCE_DB_FILE)) - { - MainDbUpgrade(); - } - else if (Database.ConnectionString.Contains(PathExtentions.LOG_SQLCE_DB_FILE)) - { - LogDbUpgrade(); - } - else - { - LogDbUpgrade(); - MainDbUpgrade(); - } - } - - protected IObjectDatabase GetObjectDb() - { - var sqlCeConnection = SqlCeProxy.EnsureDatabase(Database.ConnectionString); - - var eqPath = sqlCeConnection.Database.Replace(".sdf", ".eq"); - return new SiaqoDbFactory(new DiskProvider(),new EnvironmentProvider()).Create(eqPath); - } - - public override void Down() - { - throw new NotImplementedException(); - } - } -} diff --git a/NzbDrone.Core/Datastore/Migrations/SchemaInfo.cs b/NzbDrone.Core/Datastore/Migrations/SchemaInfo.cs deleted file mode 100644 index de23255ba..000000000 --- a/NzbDrone.Core/Datastore/Migrations/SchemaInfo.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.Linq; - -namespace NzbDrone.Core.Datastore.Migrations -{ - public class SchemaInfo - { - public int Version { get; set; } - } -} diff --git a/NzbDrone.Core/Datastore/MigrationsHelper.cs b/NzbDrone.Core/Datastore/MigrationsHelper.cs deleted file mode 100644 index 6e7cc5e14..000000000 --- a/NzbDrone.Core/Datastore/MigrationsHelper.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System.Linq; -using System; -using System.Reflection; -using NLog; - -namespace NzbDrone.Core.Datastore -{ - public class MigrationsHelper - { - private static readonly Logger logger = LogManager.GetCurrentClassLogger(); - - - public static void Run(string connectionString, bool trace) - { - SqlCeProxy.EnsureDatabase(connectionString); - - logger.Trace("Preparing to run database migration"); - - try - { - Migrator.Migrator migrator; - if (trace) - { - migrator = new Migrator.Migrator("sqlserverce", connectionString, Assembly.GetAssembly(typeof(MigrationsHelper)), true, new MigrationLogger()); - } - else - { - migrator = new Migrator.Migrator("sqlserverce", connectionString, Assembly.GetAssembly(typeof(MigrationsHelper))); - } - - migrator.MigrateToLastVersion(); - logger.Info("Database migration completed"); - - - } - catch (Exception e) - { - logger.FatalException("An error has occurred while migrating database", e); - throw; - } - } - - - - public static string GetIndexName(string tableName, params string[] columns) - { - return String.Format("IX_{0}_{1}", tableName, String.Join("_", columns)); - } - } - - - - -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/PetaPoco/EpisodeSeasonRelator.cs b/NzbDrone.Core/Datastore/PetaPoco/EpisodeSeasonRelator.cs deleted file mode 100644 index b27a4de5e..000000000 --- a/NzbDrone.Core/Datastore/PetaPoco/EpisodeSeasonRelator.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Tv; -using NzbDrone.Core.Repository; - -// ReSharper disable CheckNamespace -namespace PetaPoco -{ - public class EpisodeSeasonRelator - { - public Season _current; - public Season MapIt(Season season, Episode episode, EpisodeFile episodeFile) - { - // Terminating call. Since we can return null from this function - // we need to be ready for PetaPoco to callback later with null - // parameters - if (season == null) - return _current; - - //Todo: Find a Query that doesn't require this check - //Map EpisodeFile to Episode (Map to null if 0, because PetaPoco is returning a POCO when it should be null) - episode.EpisodeFile = (episode.EpisodeFileId == 0 ? null : episodeFile); - - // Is this the same season as the current one we're processing - if (_current != null && _current.Id == season.Id) - { - // Yes, just add this post to the current author's collection of posts - _current.Episodes.Add(episode); - - // Return null to indicate we're not done with this author yet - return null; - } - - // This is season different author to the current one, or this is the - // first time through and we don't have an season yet - - // Save the current author - var prev = _current; - - // Setup the new current season - _current = season; - _current.Episodes = new List(); - _current.Episodes.Add(episode); - - // Return the now populated previous season (or null if first time through) - return prev; - } - - } -} diff --git a/NzbDrone.Core/Datastore/PetaPoco/PetaPoco.cs b/NzbDrone.Core/Datastore/PetaPoco/PetaPoco.cs deleted file mode 100644 index 95840de21..000000000 --- a/NzbDrone.Core/Datastore/PetaPoco/PetaPoco.cs +++ /dev/null @@ -1,2708 +0,0 @@ -/* PetaPoco v4.0.3 - A Tiny ORMish thing for your POCO's. - * Copyright © 2011 Topten Software. All Rights Reserved. - * - * Apache License 2.0 - http://www.toptensoftware.com/petapoco/license - * - * Special thanks to Rob Conery (@robconery) for original inspiration (ie:Massive) and for - * use of Subsonic's T4 templates, Rob Sullivan (@DataChomp) for hard core DBA advice - * and Adam Schroder (@schotime) for lots of suggestions, improvements and Oracle support - */ - -//#define PETAPOCO_NO_DYNAMIC //in your project settings on .NET 3.5 -// ReSharper disable CheckNamespace - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Configuration; -using System.Data.Common; -using System.Data; -using System.Text.RegularExpressions; -using System.Reflection; -using System.Reflection.Emit; -using System.Linq.Expressions; - -namespace PetaPoco -{ - // Poco's marked [Explicit] require all column properties to be marked - [AttributeUsage(AttributeTargets.Class)] - public class ExplicitColumnsAttribute : Attribute - { - } - // For non-explicit pocos, causes a property to be ignored - [AttributeUsage(AttributeTargets.Property)] - public class IgnoreAttribute : Attribute - { - } - - // For explicit pocos, marks property as a column - [AttributeUsage(AttributeTargets.Property)] - public class ColumnAttribute : Attribute - { - public ColumnAttribute() { } - public ColumnAttribute(string name) { Name = name; } - public string Name { get; set; } - } - - // For explicit pocos, marks property as a column - [AttributeUsage(AttributeTargets.Property)] - public class ResultColumnAttribute : ColumnAttribute - { - public ResultColumnAttribute() { } - public ResultColumnAttribute(string name) : base(name) { } - } - - // Specify the table name of a poco - [AttributeUsage(AttributeTargets.Class)] - public class TableNameAttribute : Attribute - { - public TableNameAttribute(string tableName) - { - Value = tableName; - } - public string Value { get; private set; } - } - - // Specific the primary key of a poco class (and optional sequence name for Oracle) - [AttributeUsage(AttributeTargets.Class)] - public class PrimaryKeyAttribute : Attribute - { - public PrimaryKeyAttribute(string primaryKey) - { - Value = primaryKey; - autoIncrement = true; - } - - public string Value { get; private set; } - public string sequenceName { get; set; } - public bool autoIncrement { get; set; } - } - - [AttributeUsage(AttributeTargets.Property)] - public class AutoJoinAttribute : Attribute - { - public AutoJoinAttribute() { } - } - - [AttributeUsage(AttributeTargets.Property)] - public class VersionColumnAttribute : ColumnAttribute - { - public VersionColumnAttribute() { } - public VersionColumnAttribute(string name) : base(name) { } - } - - // Results from paged request - public class Page - { - public long CurrentPage { get; set; } - public long TotalPages { get; set; } - public long TotalItems { get; set; } - public long ItemsPerPage { get; set; } - public List Items { get; set; } - public object Context { get; set; } - } - - // Pass as parameter value to force to DBType.AnsiString - public class AnsiString - { - public AnsiString(string str) - { - Value = str; - } - public string Value { get; private set; } - } - - // Used by IMapper to override table bindings for an object - public class TableInfo - { - public string TableName { get; set; } - public string PrimaryKey { get; set; } - public bool AutoIncrement { get; set; } - public string SequenceName { get; set; } - } - - // Optionally provide an implementation of this to Database.Mapper - public interface IMapper - { - void GetTableInfo(Type t, TableInfo ti); - bool MapPropertyToColumn(PropertyInfo pi, ref string columnName, ref bool resultColumn); - Func GetFromDbConverter(PropertyInfo pi, Type SourceType); - Func GetToDbConverter(Type SourceType); - } - - // This will be merged with IMapper in the next major version - public interface IMapper2 : IMapper - { - Func GetFromDbConverter(Type DestType, Type SourceType); - } - - public class DefaultMapper : IMapper2 - { - public virtual void GetTableInfo(Type t, TableInfo ti) { } - public virtual bool MapPropertyToColumn(PropertyInfo pi, ref string columnName, ref bool resultColumn) - { - return true; - } - public virtual Func GetFromDbConverter(PropertyInfo pi, Type SourceType) - { - return null; - } - public virtual Func GetToDbConverter(Type SourceType) - { - return null; - } - public virtual Func GetFromDbConverter(Type DestType, Type SourceType) - { - return null; - } - } - - //public class DestinationInfo - //{ - // public DestinationInfo(Type type) - // { - // Type = type; - // } - - // public DestinationInfo(PropertyInfo propertyInfo) - // { - // PropertyInfo = propertyInfo; - // Type = propertyInfo.PropertyType; - // } - - // public PropertyInfo PropertyInfo { get; private set; } - // public Type Type { get; private set; } - //} - - public interface IDatabaseQuery - { - void OpenSharedConnection(); - void CloseSharedConnection(); - int Execute(string sql, params object[] args); - int Execute(Sql sql); - T ExecuteScalar(string sql, params object[] args); - T ExecuteScalar(Sql sql); - List Fetch(); - List Fetch(string sql, params object[] args); - List Fetch(Sql sql); - List Fetch(long page, long itemsPerPage, string sql, params object[] args); - List Fetch(long page, long itemsPerPage, Sql sql); - Page Page(long page, long itemsPerPage, string sql, params object[] args); - Page Page(long page, long itemsPerPage, Sql sql); - List SkipTake(long skip, long take, string sql, params object[] args); - List SkipTake(long skip, long take, Sql sql); - List Fetch(Func cb, string sql, params object[] args); - List Fetch(Func cb, string sql, params object[] args); - List Fetch(Func cb, string sql, params object[] args); - IEnumerable Query(Func cb, string sql, params object[] args); - IEnumerable Query(Func cb, string sql, params object[] args); - IEnumerable Query(Func cb, string sql, params object[] args); - List Fetch(Func cb, Sql sql); - List Fetch(Func cb, Sql sql); - List Fetch(Func cb, Sql sql); - IEnumerable Query(Func cb, Sql sql); - IEnumerable Query(Func cb, Sql sql); - IEnumerable Query(Func cb, Sql sql); - List Fetch(string sql, params object[] args); - List Fetch(string sql, params object[] args); - List Fetch(string sql, params object[] args); - IEnumerable Query(string sql, params object[] args); - IEnumerable Query(string sql, params object[] args); - IEnumerable Query(string sql, params object[] args); - IEnumerable Query(Type[] types, object cb, string sql, params object[] args); - List Fetch(Sql sql); - List Fetch(Sql sql); - List Fetch(Sql sql); - IEnumerable Query(Sql sql); - IEnumerable Query(Sql sql); - IEnumerable Query(Sql sql); - IEnumerable Query(string sql, params object[] args); - IEnumerable Query(Sql sql); - T Single(object primaryKey); - T SingleOrDefault(object primaryKey); - T Single(string sql, params object[] args); - T SingleOrDefault(string sql, params object[] args); - T First(string sql, params object[] args); - T FirstOrDefault(string sql, params object[] args); - T Single(Sql sql); - T SingleOrDefault(Sql sql); - T First(Sql sql); - T FirstOrDefault(Sql sql); - bool Exists(object primaryKey); - int OneTimeCommandTimeout { get; set; } - bool Exists(string sql, params object[] args); - } - - public interface IDatabase : IDatabaseQuery - { - void Dispose(); - IDbConnection Connection { get; } - ITransaction GetTransaction(); - Transaction GetTransaction(IsolationLevel? isolationLevel); - void BeginTransaction(); - void BeginTransaction(IsolationLevel? isolationLevel); - void AbortTransaction(); - void CompleteTransaction(); - object Insert(string tableName, string primaryKeyName, bool autoIncrement, object poco); - object Insert(string tableName, string primaryKeyName, object poco); - object Insert(object poco); - int Update(string tableName, string primaryKeyName, object poco, object primaryKeyValue); - int Update(string tableName, string primaryKeyName, object poco); - int Update(string tableName, string primaryKeyName, object poco, object primaryKeyValue, IEnumerable columns); - int Update(string tableName, string primaryKeyName, object poco, IEnumerable columns); - int Update(object poco, IEnumerable columns); - int Update(object poco, object primaryKeyValue, IEnumerable columns); - int Update(object poco); - int Update(object poco, object primaryKeyValue); - int Update(string sql, params object[] args); - int Update(Sql sql); - void UpdateMany(IEnumerable pocoList); - int Delete(string tableName, string primaryKeyName, object poco); - int Delete(string tableName, string primaryKeyName, object poco, object primaryKeyValue); - int Delete(object poco); - int Delete(string sql, params object[] args); - int Delete(Sql sql); - int Delete(object pocoOrPrimaryKey); - void Save(string tableName, string primaryKeyName, object poco); - void Save(object poco); - void InsertMany(IEnumerable pocoList); - void SaveMany(IEnumerable pocoList); - } - - // Database class ... this is where most of the action happens - public class Database : IDisposable, IDatabase - { - public const string MsSqlClientProvider = "System.Data.SqlClient"; - - public Database(IDbConnection connection) : this(connection, DBType.NotSet) { } - - public Database(IDbConnection connection, DBType dbType) - { - _sharedConnection = connection; - _connectionString = connection.ConnectionString; - - _dbType = dbType; - CommonConstruct(); - } - - public Database(string connectionString, string providerName) - { - _connectionString = connectionString; - _providerName = providerName; - CommonConstruct(); - } - - public Database(string connectionString, DbProviderFactory provider, DBType dbType) - { - _connectionString = connectionString; - _factory = provider; - _dbType = dbType; - CommonConstruct(); - } - - public Database(string connectionStringName) - { - // Use first? - if (connectionStringName == "") - connectionStringName = ConfigurationManager.ConnectionStrings[0].Name; - - // Work out connection string and provider name - var providerName = "System.Data.SqlClient"; - if (ConfigurationManager.ConnectionStrings[connectionStringName] != null) - { - if (!string.IsNullOrEmpty(ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName)) - providerName = ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName; - } - else - { - throw new InvalidOperationException("Can't find a connection string with the name '" + connectionStringName + "'"); - } - - // Store factory and connection string - _connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; - _providerName = providerName; - CommonConstruct(); - } - - public enum DBType - { - NotSet, - SqlServer, - SqlServerCE, - MySql, - PostgreSQL, - Oracle, - SQLite - } - - private DBType _dbType = DBType.NotSet; - - // Common initialization - private void CommonConstruct() - { - ForceDateTimesToUtc = true; - EnableAutoSelect = true; - - if (_providerName != null) - _factory = DbProviderFactories.GetFactory(_providerName); - - if (_dbType == DBType.NotSet) - { - _dbType = DBType.SqlServer; - string dbtype = (_factory == null ? _sharedConnection.GetType() : _factory.GetType()).Name; - if (dbtype.StartsWith("MySql")) - _dbType = DBType.MySql; - else if (dbtype.StartsWith("SqlCe")) - _dbType = DBType.SqlServerCE; - else if (dbtype.StartsWith("Npgsql")) - _dbType = DBType.PostgreSQL; - else if (dbtype.StartsWith("Oracle")) - _dbType = DBType.Oracle; - else if (dbtype.StartsWith("SQLite")) - _dbType = DBType.SQLite; - } - - if (_dbType == DBType.MySql && _connectionString != null && _connectionString.IndexOf("Allow User Variables=true") >= 0) - _paramPrefix = "?"; - if (_dbType == DBType.Oracle) - _paramPrefix = ":"; - } - - // Automatically close one open shared connection - public void Dispose() - { - // Automatically close one open connection reference - // (Works with KeepConnectionAlive and manually opening a shared connection) - KeepConnectionAlive = false; - CloseSharedConnection(); - } - - // Set to true to keep the first opened connection alive until this object is disposed - public bool KeepConnectionAlive { get; set; } - - // Open a connection (can be nested) - public void OpenSharedConnection() - { - if (_sharedConnection == null || _sharedConnection.State == ConnectionState.Closed || _sharedConnection.State == ConnectionState.Broken) - { - _sharedConnection = _factory.CreateConnection(); - _sharedConnection.ConnectionString = _connectionString; - _sharedConnection.Open(); - - _sharedConnection = OnConnectionOpened(_sharedConnection); - } - } - - /// - /// Close a previously opened connection - /// - // Close a previously opened connection - public void CloseSharedConnection() - { - if (!KeepConnectionAlive && _sharedConnection != null) - { - OnConnectionClosing(_sharedConnection); - _sharedConnection.Dispose(); - _sharedConnection = null; - _transaction = null; - } - } - - // Access to our shared connection - public IDbConnection Connection - { - get { return _sharedConnection; } - } - - // Helper to create a transaction scope - public ITransaction GetTransaction() - { - return GetTransaction(null); - } - - public Transaction GetTransaction(IsolationLevel? isolationLevel) - { - return new Transaction(this, isolationLevel); - } - - // Use by derived repo generated by T4 templates - public virtual void OnBeginTransaction() { } - public virtual void OnEndTransaction() { } - - public void BeginTransaction() - { - BeginTransaction(null); - } - - // Start a new transaction, can be nested, every call must be - // matched by a call to AbortTransaction or CompleteTransaction - // Use `using (var scope=db.Transaction) { scope.Complete(); }` to ensure correct semantics - public void BeginTransaction(IsolationLevel? isolationLevel) - { - OpenSharedConnection(); - _transaction = isolationLevel == null ? _sharedConnection.BeginTransaction() : _sharedConnection.BeginTransaction(isolationLevel.Value); - _transactionCancelled = false; - OnBeginTransaction(); - - - } - - // Internal helper to cleanup transaction stuff - void CleanupTransaction() - { - OnEndTransaction(); - - if (_transactionCancelled) - _transaction.Rollback(); - else - _transaction.Commit(); - - _transaction.Dispose(); - _transaction = null; - - CloseSharedConnection(); - } - - // Abort the entire outer most transaction scope - public void AbortTransaction() - { - _transactionCancelled = true; - CleanupTransaction(); - } - - // Complete the transaction - public void CompleteTransaction() - { - CleanupTransaction(); - } - - // Helper to handle named parameters from object properties - static Regex rxParams = new Regex(@"(? args_dest) - { - return rxParams.Replace(_sql, m => - { - string param = m.Value.Substring(1); - - object arg_val; - - int paramIndex; - if (int.TryParse(param, out paramIndex)) - { - // Numbered parameter - if (paramIndex < 0 || paramIndex >= args_src.Length) - throw new ArgumentOutOfRangeException(string.Format("Parameter '@{0}' specified but only {1} parameters supplied (in `{2}`)", paramIndex, args_src.Length, _sql)); - arg_val = args_src[paramIndex]; - } - else - { - // Look for a property on one of the arguments with this name - bool found = false; - arg_val = null; - foreach (var o in args_src) - { - var pi = o.GetType().GetProperty(param); - if (pi != null) - { - arg_val = pi.GetValue(o, null); - found = true; - break; - } - } - - if (!found) - throw new ArgumentException(string.Format("Parameter '@{0}' specified but none of the passed arguments have a property with this name (in '{1}')", param, _sql)); - } - - // Expand collections to parameter lists - if ((arg_val as System.Collections.IEnumerable) != null && - (arg_val as string) == null && - (arg_val as byte[]) == null) - { - var sb = new StringBuilder(); - foreach (var i in arg_val as System.Collections.IEnumerable) - { - var indexOfExistingValue = args_dest.IndexOf(i); - if (indexOfExistingValue >= 0) - { - sb.Append((sb.Length == 0 ? "@" : ",@") + indexOfExistingValue); - } - else - { - sb.Append((sb.Length == 0 ? "@" : ",@") + args_dest.Count); - args_dest.Add(i); - } - } - return sb.ToString(); - } - else - { - var indexOfExistingValue = args_dest.IndexOf(arg_val); - if (indexOfExistingValue >= 0) - return "@" + indexOfExistingValue; - - args_dest.Add(arg_val); - return "@" + (args_dest.Count - 1).ToString(); - } - } - ); - } - - // Add a parameter to a DB command - void AddParam(IDbCommand cmd, object item, string ParameterPrefix) - { - // Convert value to from poco type to db type - if (Database.Mapper != null && item != null) - { - var fn = Database.Mapper.GetToDbConverter(item.GetType()); - if (fn != null) - item = fn(item); - } - - // Support passed in parameters - var idbParam = item as IDbDataParameter; - if (idbParam != null) - { - idbParam.ParameterName = string.Format("{0}{1}", ParameterPrefix, cmd.Parameters.Count); - cmd.Parameters.Add(idbParam); - return; - } - var p = cmd.CreateParameter(); - p.ParameterName = string.Format("{0}{1}", ParameterPrefix, cmd.Parameters.Count); - - if (item == null) - { - p.Value = DBNull.Value; - } - else - { - var t = item.GetType(); - if (t.IsEnum) // PostgreSQL .NET driver wont cast enum to int - { - p.Value = (int)item; - } - else if (t == typeof(Guid)) - { - p.Value = item.ToString(); - p.DbType = DbType.String; - p.Size = 40; - } - else if (t == typeof(string)) - { - p.Size = Math.Max((item as string).Length + 1, 4000); // Help query plan caching by using common size - p.Value = item; - } - else if (t == typeof(AnsiString)) - { - // Thanks @DataChomp for pointing out the SQL Server indexing performance hit of using wrong string type on varchar - p.Size = Math.Max((item as AnsiString).Value.Length + 1, 4000); - p.Value = (item as AnsiString).Value; - p.DbType = DbType.AnsiString; - } - else if (t == typeof(bool) && _dbType != DBType.PostgreSQL) - { - p.Value = ((bool)item) ? 1 : 0; - } - else if (item.GetType().Name == "SqlGeography") //SqlGeography is a CLR Type - { - p.GetType().GetProperty("UdtTypeName").SetValue(p, "geography", null); //geography is the equivalent SQL Server Type - p.Value = item; - } - - else if (item.GetType().Name == "SqlGeometry") //SqlGeometry is a CLR Type - { - p.GetType().GetProperty("UdtTypeName").SetValue(p, "geometry", null); //geography is the equivalent SQL Server Type - p.Value = item; - } - else - { - p.Value = item; - } - } - - cmd.Parameters.Add(p); - } - - // Create a command - static Regex rxParamsPrefix = new Regex(@"(? _paramPrefix + m.Value.Substring(1)); - sql = sql.Replace("@@", "@"); // <- double @@ escapes a single @ - - // Create the command and add parameters - IDbCommand cmd = connection.CreateCommand(); - cmd.Connection = connection; - cmd.CommandText = sql; - cmd.Transaction = _transaction; - - foreach (var item in args) - { - AddParam(cmd, item, _paramPrefix); - } - - if (_dbType == DBType.Oracle) - { - cmd.GetType().GetProperty("BindByName").SetValue(cmd, true, null); - } - - if (!String.IsNullOrEmpty(sql)) - DoPreExecute(cmd); - - return cmd; - } - - // Create a command - //IDbCommand CreateCommand(IDbConnection connection, string sql, params object[] args) - //{ - // var sqlStatement = new Sql(sql, args); - // return CreateCommand(connection, sqlStatement); - //} - - // Override this to log/capture exceptions - public virtual void OnException(Exception x) - { - System.Diagnostics.Debug.WriteLine(x.ToString()); - System.Diagnostics.Debug.WriteLine(LastCommand); - } - - // Override this to log commands, or modify command before execution - public virtual IDbConnection OnConnectionOpened(IDbConnection conn) { return conn; } - public virtual void OnConnectionClosing(IDbConnection conn) { } - public virtual void OnExecutingCommand(IDbCommand cmd) { } - public virtual void OnExecutedCommand(IDbCommand cmd) { } - - // Execute a non-query command - public int Execute(string sql, params object[] args) - { - return Execute(new Sql(sql, args)); - } - - public int Execute(Sql Sql) - { - var sql = Sql.SQL; - var args = Sql.Arguments; - - try - { - OpenSharedConnection(); - try - { - using (var cmd = CreateCommand(_sharedConnection, sql, args)) - { - var result = cmd.ExecuteNonQuery(); - OnExecutedCommand(cmd); - return result; - } - } - finally - { - CloseSharedConnection(); - } - } - catch (Exception x) - { - OnException(x); - throw; - } - } - - // Execute and cast a scalar property - public T ExecuteScalar(string sql, params object[] args) - { - return ExecuteScalar(new Sql(sql, args)); - } - - public T ExecuteScalar(Sql Sql) - { - var sql = Sql.SQL; - var args = Sql.Arguments; - - try - { - OpenSharedConnection(); - try - { - using (var cmd = CreateCommand(_sharedConnection, sql, args)) - { - object val = cmd.ExecuteScalar(); - OnExecutedCommand(cmd); - return (T)Convert.ChangeType(val, typeof(T)); - } - } - finally - { - CloseSharedConnection(); - } - } - catch (Exception x) - { - OnException(x); - throw; - } - } - - static Regex rxSelect = new Regex(@"\A\s*(SELECT|EXECUTE|CALL)\s", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Multiline); - static Regex rxFrom = new Regex(@"\A\s*FROM\s", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Multiline); - string AddSelectClause(string sql) - { - if (sql.StartsWith(";")) - return sql.Substring(1); - - if (!rxSelect.IsMatch(sql)) - { - var pd = PocoData.ForType(typeof(T)); - var tableName = EscapeTableName(pd.TableInfo.TableName); - string cols = string.Join(", ", (from c in pd.QueryColumns select EscapeSqlIdentifier(c)).ToArray()); - if (!rxFrom.IsMatch(sql)) - sql = string.Format("SELECT {0} FROM {1} {2}", cols, tableName, sql); - else - sql = string.Format("SELECT {0} {1}", cols, sql); - } - return sql; - } - - public bool ForceDateTimesToUtc { get; set; } - public bool EnableAutoSelect { get; set; } - - // Return a typed list of pocos - public List Fetch(string sql, params object[] args) - { - return Fetch(new Sql(sql, args)); - } - - public List Fetch(Sql sql) - { - return Query(sql).ToList(); - } - - public List Fetch() - { - return Fetch(""); - } - - static Regex rxColumns = new Regex(@"\A\s*SELECT\s+((?:\((?>\((?)|\)(?<-depth>)|.?)*(?(depth)(?!))\)|.)*?)(?\((?)|\)(?<-depth>)|.?)*(?(depth)(?!))\)|[\w\(\)\.])+(?:\s+(?:ASC|DESC))?(?:\s*,\s*(?:\((?>\((?)|\)(?<-depth>)|.?)*(?(depth)(?!))\)|[\w\(\)\.])+(?:\s+(?:ASC|DESC))?)*", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.Compiled); - static Regex rxDistinct = new Regex(@"\ADISTINCT\s", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.Compiled); - public static bool SplitSqlForPaging(string sql, out string sqlCount, out string sqlSelectRemoved, out string sqlOrderBy) - { - sqlSelectRemoved = null; - sqlCount = null; - sqlOrderBy = null; - - // Extract the columns from "SELECT FROM" - var m = rxColumns.Match(sql); - if (!m.Success) - return false; - - // Save column list and replace with COUNT(*) - Group g = m.Groups[1]; - sqlSelectRemoved = sql.Substring(g.Index); - - if (rxDistinct.IsMatch(sqlSelectRemoved)) - sqlCount = sql.Substring(0, g.Index) + "COUNT(" + m.Groups[1].ToString().Trim() + ") " + sql.Substring(g.Index + g.Length); - else - sqlCount = sql.Substring(0, g.Index) + "COUNT(*) " + sql.Substring(g.Index + g.Length); - - - // Look for an "ORDER BY " clause - m = rxOrderBy.Match(sqlCount); - if (m.Success) - { - g = m.Groups[0]; - sqlOrderBy = g.ToString(); - sqlCount = sqlCount.Substring(0, g.Index) + sqlCount.Substring(g.Index + g.Length); - } - - return true; - } - - public void BuildPageQueries(long skip, long take, string sql, ref object[] args, out string sqlCount, out string sqlPage) - { - // Add auto select clause - sql = AddSelectClause(sql); - - // Split the SQL into the bits we need - string sqlSelectRemoved, sqlOrderBy; - if (!SplitSqlForPaging(sql, out sqlCount, out sqlSelectRemoved, out sqlOrderBy)) - throw new Exception("Unable to parse SQL statement for paged query"); - if (_dbType == DBType.Oracle && sqlSelectRemoved.StartsWith("*")) - throw new Exception("Query must alias '*' when performing a paged query.\neg. select t.* from table t order by t.id"); - - // Build the SQL for the actual final result - if (_dbType == DBType.SqlServer || _dbType == DBType.Oracle) - { - sqlSelectRemoved = rxOrderBy.Replace(sqlSelectRemoved, ""); - if (rxDistinct.IsMatch(sqlSelectRemoved)) - { - sqlSelectRemoved = "peta_inner.* FROM (SELECT " + sqlSelectRemoved + ") peta_inner"; - } - sqlPage = string.Format("SELECT * FROM (SELECT ROW_NUMBER() OVER ({0}) peta_rn, {1}) peta_paged WHERE peta_rn>@{2} AND peta_rn<=@{3}", - sqlOrderBy == null ? "ORDER BY (SELECT NULL)" : sqlOrderBy, sqlSelectRemoved, args.Length, args.Length + 1); - args = args.Concat(new object[] { skip, skip + take }).ToArray(); - } - else if (_dbType == DBType.SqlServerCE) - { - sqlPage = string.Format("{0}\nOFFSET @{1} ROWS FETCH NEXT @{2} ROWS ONLY", sql, args.Length, args.Length + 1); - args = args.Concat(new object[] { skip, take }).ToArray(); - } - else - { - sqlPage = string.Format("{0}\nLIMIT @{1} OFFSET @{2}", sql, args.Length, args.Length + 1); - args = args.Concat(new object[] { take, skip }).ToArray(); - } - - } - - // Fetch a page - public Page Page(long page, long itemsPerPage, string sql, params object[] args) - { - string sqlCount, sqlPage; - BuildPageQueries((page - 1) * itemsPerPage, itemsPerPage, sql, ref args, out sqlCount, out sqlPage); - - // Save the one-time command time out and use it for both queries - int saveTimeout = OneTimeCommandTimeout; - - // Setup the paged result - var result = new Page(); - result.CurrentPage = page; - result.ItemsPerPage = itemsPerPage; - result.TotalItems = ExecuteScalar(sqlCount, args); - result.TotalPages = result.TotalItems / itemsPerPage; - if ((result.TotalItems % itemsPerPage) != 0) - result.TotalPages++; - - OneTimeCommandTimeout = saveTimeout; - - // Get the records - result.Items = Fetch(sqlPage, args); - - // Done - return result; - } - - public Page Page(long page, long itemsPerPage, Sql sql) - { - return Page(page, itemsPerPage, sql.SQL, sql.Arguments); - } - - public List Fetch(long page, long itemsPerPage, string sql, params object[] args) - { - return SkipTake((page - 1) * itemsPerPage, itemsPerPage, sql, args); - } - - public List Fetch(long page, long itemsPerPage, Sql sql) - { - return SkipTake((page - 1) * itemsPerPage, itemsPerPage, sql.SQL, sql.Arguments); - } - - public List SkipTake(long skip, long take, string sql, params object[] args) - { - string sqlCount, sqlPage; - BuildPageQueries(skip, take, sql, ref args, out sqlCount, out sqlPage); - return Fetch(sqlPage, args); - } - - public List SkipTake(long skip, long take, Sql sql) - { - return SkipTake(skip, take, sql.SQL, sql.Arguments); - } - - public Dictionary Dictionary(Sql Sql) - { - return Dictionary(Sql.SQL, Sql.Arguments); - } - - public Dictionary Dictionary(string sql, params object[] args) - { - var newDict = new Dictionary(); - bool isConverterSet = false; - Func converter1 = x => x, converter2 = x => x; - - foreach (var line in Query>(sql, args)) - { - object key = line.ElementAt(0).Value; - object value = line.ElementAt(1).Value; - - if (isConverterSet == false) - { - converter1 = PocoData.GetConverter(ForceDateTimesToUtc, null, typeof(TKey), key.GetType()) ?? (x => x); - converter2 = PocoData.GetConverter(ForceDateTimesToUtc, null, typeof(TValue), value.GetType()) ?? (x => x); - isConverterSet = true; - } - - var keyConverted = (TKey)Convert.ChangeType(converter1(key), typeof(TKey)); - - var valueType = Nullable.GetUnderlyingType(typeof(TValue)) ?? typeof(TValue); - var valConv = converter2(value); - var valConverted = valConv != null ? (TValue)Convert.ChangeType(valConv, valueType) : default(TValue); - - if (keyConverted != null) - { - newDict.Add(keyConverted, valConverted); - } - } - return newDict; - } - - // Return an enumerable collection of pocos - public IEnumerable Query(string sql, params object[] args) - { - return Query(new Sql(sql, args)); - } - - public IEnumerable Query(Sql Sql) - { - var sql = Sql.SQL; - var args = Sql.Arguments; - - if (EnableAutoSelect) - sql = AddSelectClause(sql); - - OpenSharedConnection(); - try - { - using (var cmd = CreateCommand(_sharedConnection, sql, args)) - { - IDataReader r; - var pd = PocoData.ForType(typeof(T)); - try - { - r = cmd.ExecuteReader(); - OnExecutedCommand(cmd); - } - catch (Exception x) - { - OnException(x); - throw; - } - - using (r) - { - var factory = pd.GetFactory(cmd.CommandText, _sharedConnection.ConnectionString, ForceDateTimesToUtc, 0, r.FieldCount, r) as Func; - while (true) - { - T poco; - try - { - if (!r.Read()) - yield break; - poco = factory(r); - } - catch (Exception x) - { - OnException(x); - throw; - } - - yield return poco; - } - } - } - } - finally - { - CloseSharedConnection(); - } - } - - // Multi Fetch - public List Fetch(Func cb, string sql, params object[] args) { return Query(cb, sql, args).ToList(); } - public List Fetch(Func cb, string sql, params object[] args) { return Query(cb, sql, args).ToList(); } - public List Fetch(Func cb, string sql, params object[] args) { return Query(cb, sql, args).ToList(); } - - // Multi Query - public IEnumerable Query(Func cb, string sql, params object[] args) { return Query(new Type[] { typeof(T1), typeof(T2) }, cb, sql, args); } - public IEnumerable Query(Func cb, string sql, params object[] args) { return Query(new Type[] { typeof(T1), typeof(T2), typeof(T3) }, cb, sql, args); } - public IEnumerable Query(Func cb, string sql, params object[] args) { return Query(new Type[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) }, cb, sql, args); } - - // Multi Fetch (SQL builder) - public List Fetch(Func cb, Sql sql) { return Query(cb, sql.SQL, sql.Arguments).ToList(); } - public List Fetch(Func cb, Sql sql) { return Query(cb, sql.SQL, sql.Arguments).ToList(); } - public List Fetch(Func cb, Sql sql) { return Query(cb, sql.SQL, sql.Arguments).ToList(); } - - // Multi Query (SQL builder) - public IEnumerable Query(Func cb, Sql sql) { return Query(new Type[] { typeof(T1), typeof(T2) }, cb, sql.SQL, sql.Arguments); } - public IEnumerable Query(Func cb, Sql sql) { return Query(new Type[] { typeof(T1), typeof(T2), typeof(T3) }, cb, sql.SQL, sql.Arguments); } - public IEnumerable Query(Func cb, Sql sql) { return Query(new Type[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) }, cb, sql.SQL, sql.Arguments); } - - // Multi Fetch (Simple) - public List Fetch(string sql, params object[] args) { return Query(sql, args).ToList(); } - public List Fetch(string sql, params object[] args) { return Query(sql, args).ToList(); } - public List Fetch(string sql, params object[] args) { return Query(sql, args).ToList(); } - - // Multi Query (Simple) - public IEnumerable Query(string sql, params object[] args) { return Query(new Type[] { typeof(T1), typeof(T2) }, null, sql, args); } - public IEnumerable Query(string sql, params object[] args) { return Query(new Type[] { typeof(T1), typeof(T2), typeof(T3) }, null, sql, args); } - public IEnumerable Query(string sql, params object[] args) { return Query(new Type[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) }, null, sql, args); } - - // Multi Fetch (Simple) (SQL builder) - public List Fetch(Sql sql) { return Query(sql.SQL, sql.Arguments).ToList(); } - public List Fetch(Sql sql) { return Query(sql.SQL, sql.Arguments).ToList(); } - public List Fetch(Sql sql) { return Query(sql.SQL, sql.Arguments).ToList(); } - - // Multi Query (Simple) (SQL builder) - public IEnumerable Query(Sql sql) { return Query(new Type[] { typeof(T1), typeof(T2) }, null, sql.SQL, sql.Arguments); } - public IEnumerable Query(Sql sql) { return Query(new Type[] { typeof(T1), typeof(T2), typeof(T3) }, null, sql.SQL, sql.Arguments); } - public IEnumerable Query(Sql sql) { return Query(new Type[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) }, null, sql.SQL, sql.Arguments); } - - // Automagically guess the property relationships between various POCOs and create a delegate that will set them up - object GetAutoMapper(Type[] types) - { - // Build a key - var kb = new StringBuilder(); - foreach (var t in types) - { - kb.Append(t.ToString()); - kb.Append(":"); - } - var key = kb.ToString(); - - // Check cache - RWLock.EnterReadLock(); - try - { - object mapper; - if (AutoMappers.TryGetValue(key, out mapper)) - return mapper; - } - finally - { - RWLock.ExitReadLock(); - } - - // Create it - RWLock.EnterWriteLock(); - try - { - // Try again - object mapper; - if (AutoMappers.TryGetValue(key, out mapper)) - return mapper; - - // Create a method - var m = new DynamicMethod("petapoco_automapper", types[0], types, true); - var il = m.GetILGenerator(); - - for (int i = 1; i < types.Length; i++) - { - bool handled = false; - for (int j = i - 1; j >= 0; j--) - { - // Find the property - var candidates = from p in types[j].GetProperties() where p.PropertyType == types[i] select p; - if (candidates.Count() == 0) - continue; - if (candidates.Count() > 1) - throw new InvalidOperationException(string.Format("Can't auto join {0} as {1} has more than one property of type {0}", types[i], types[j])); - - // Generate code - il.Emit(OpCodes.Ldarg_S, j); - il.Emit(OpCodes.Ldarg_S, i); - il.Emit(OpCodes.Callvirt, candidates.First().GetSetMethod(true)); - handled = true; - } - - if (!handled) - throw new InvalidOperationException(string.Format("Can't auto join {0}", types[i])); - } - - il.Emit(OpCodes.Ldarg_0); - il.Emit(OpCodes.Ret); - - // Cache it - var del = m.CreateDelegate(Expression.GetFuncType(types.Concat(types.Take(1)).ToArray())); - AutoMappers.Add(key, del); - return del; - } - finally - { - RWLock.ExitWriteLock(); - } - } - - // Find the split point in a result set for two different pocos and return the poco factory for the first - Delegate FindSplitPoint(Type typeThis, Type typeNext, string sql, IDataReader r, ref int pos) - { - // Last? - if (typeNext == null) - return PocoData.ForType(typeThis).GetFactory(sql, _sharedConnection.ConnectionString, ForceDateTimesToUtc, pos, r.FieldCount - pos, r); - - // Get PocoData for the two types - PocoData pdThis = PocoData.ForType(typeThis); - PocoData pdNext = PocoData.ForType(typeNext); - - // Find split point - int firstColumn = pos; - var usedColumns = new Dictionary(); - for (; pos < r.FieldCount; pos++) - { - // Split if field name has already been used, or if the field doesn't exist in current poco but does in the next - string fieldName = r.GetName(pos); - if (usedColumns.ContainsKey(fieldName) || (!pdThis.Columns.ContainsKey(fieldName) && pdNext.Columns.ContainsKey(fieldName))) - { - return pdThis.GetFactory(sql, _sharedConnection.ConnectionString, ForceDateTimesToUtc, firstColumn, pos - firstColumn, r); - } - usedColumns.Add(fieldName, true); - } - - throw new InvalidOperationException(string.Format("Couldn't find split point between {0} and {1}", typeThis, typeNext)); - } - - // Instance data used by the Multipoco factory delegate - essentially a list of the nested poco factories to call - class MultiPocoFactory - { - public List m_Delegates; - public Delegate GetItem(int index) { return m_Delegates[index]; } - } - - // Create a multi-poco factory - Func CreateMultiPocoFactory(Type[] types, string sql, IDataReader r) - { - var m = new DynamicMethod("petapoco_multipoco_factory", typeof(TRet), new Type[] { typeof(MultiPocoFactory), typeof(IDataReader), typeof(object) }, typeof(MultiPocoFactory)); - var il = m.GetILGenerator(); - - // Load the callback - il.Emit(OpCodes.Ldarg_2); - - // Call each delegate - var dels = new List(); - int pos = 0; - for (int i = 0; i < types.Length; i++) - { - // Add to list of delegates to call - var del = FindSplitPoint(types[i], i + 1 < types.Length ? types[i + 1] : null, sql, r, ref pos); - dels.Add(del); - - // Get the delegate - il.Emit(OpCodes.Ldarg_0); // callback,this - il.Emit(OpCodes.Ldc_I4, i); // callback,this,Index - il.Emit(OpCodes.Callvirt, typeof(MultiPocoFactory).GetMethod("GetItem")); // callback,Delegate - il.Emit(OpCodes.Ldarg_1); // callback,delegate, datareader - - // Call Invoke - var tDelInvoke = del.GetType().GetMethod("Invoke"); - il.Emit(OpCodes.Callvirt, tDelInvoke); // Poco left on stack - } - - // By now we should have the callback and the N pocos all on the stack. Call the callback and we're done - il.Emit(OpCodes.Callvirt, Expression.GetFuncType(types.Concat(new Type[] { typeof(TRet) }).ToArray()).GetMethod("Invoke")); - il.Emit(OpCodes.Ret); - - // Finish up - return (Func)m.CreateDelegate(typeof(Func), new MultiPocoFactory() { m_Delegates = dels }); - } - - // Various cached stuff - static Dictionary MultiPocoFactories = new Dictionary(); - static Dictionary AutoMappers = new Dictionary(); - static System.Threading.ReaderWriterLockSlim RWLock = new System.Threading.ReaderWriterLockSlim(); - - // Get (or create) the multi-poco factory for a query - Func GetMultiPocoFactory(Type[] types, string sql, IDataReader r) - { - // Build a key string (this is crap, should address this at some point) - var kb = new StringBuilder(); - kb.Append(typeof(TRet).ToString()); - kb.Append(":"); - foreach (var t in types) - { - kb.Append(":"); - kb.Append(t.ToString()); - } - kb.Append(":"); kb.Append(_sharedConnection.ConnectionString); - kb.Append(":"); kb.Append(ForceDateTimesToUtc); - kb.Append(":"); kb.Append(sql); - string key = kb.ToString(); - - // Check cache - RWLock.EnterReadLock(); - try - { - object oFactory; - if (MultiPocoFactories.TryGetValue(key, out oFactory)) - return (Func)oFactory; - } - finally - { - RWLock.ExitReadLock(); - } - - // Cache it - RWLock.EnterWriteLock(); - try - { - // Check again - object oFactory; - if (MultiPocoFactories.TryGetValue(key, out oFactory)) - return (Func)oFactory; - - // Create the factory - var Factory = CreateMultiPocoFactory(types, sql, r); - - MultiPocoFactories.Add(key, Factory); - return Factory; - } - finally - { - RWLock.ExitWriteLock(); - } - - } - - // Actual implementation of the multi-poco query - public IEnumerable Query(Type[] types, object cb, string sql, params object[] args) - { - OpenSharedConnection(); - try - { - using (var cmd = CreateCommand(_sharedConnection, sql, args)) - { - IDataReader r; - try - { - r = cmd.ExecuteReader(); - OnExecutedCommand(cmd); - } - catch (Exception x) - { - OnException(x); - throw; - } - var factory = GetMultiPocoFactory(types, sql, r); - if (cb == null) - cb = GetAutoMapper(types.ToArray()); - bool bNeedTerminator = false; - using (r) - { - while (true) - { - TRet poco; - try - { - if (!r.Read()) - break; - poco = factory(r, cb); - } - catch (Exception x) - { - OnException(x); - throw; - } - - if (poco != null) - yield return poco; - else - bNeedTerminator = true; - } - if (bNeedTerminator) - { - var poco = (TRet)(cb as Delegate).DynamicInvoke(new object[types.Length]); - if (poco != null) - yield return poco; - else - yield break; - } - } - } - } - finally - { - CloseSharedConnection(); - } - } - - public bool Exists(object primaryKey) - { - var index = 0; - var primaryKeyValuePairs = GetPrimaryKeyValues(PocoData.ForType(typeof(T)).TableInfo.PrimaryKey, primaryKey); - return FirstOrDefault(string.Format("WHERE {0}", BuildPrimaryKeySql(primaryKeyValuePairs, ref index)), primaryKeyValuePairs.Select(x => x.Value).ToArray()) != null; - } - - - public bool Exists(string sql, params object[] args) - { - var poco = PocoData.ForType(typeof(T)).TableInfo; - - string existsTemplate; - - switch (_dbType) - { - case DBType.SQLite: - case DBType.MySql: - { - existsTemplate = "SELECT EXISTS (SELECT 1 FROM {0} {1})"; - break; - } - - case DBType.SqlServer: - { - existsTemplate = "IF EXISTS (SELECT 1 FROM {0} {1}) SELECT 1 ELSE SELECT 0"; - break; - } - default: - { - existsTemplate = "SELECT COUNT(*) FROM {0} {1}"; - break; - } - } - - - return ExecuteScalar(string.Format(existsTemplate, poco.TableName, sql), args) != 0; - } - public T Single(object primaryKey) - { - var index = 0; - var primaryKeyValuePairs = GetPrimaryKeyValues(PocoData.ForType(typeof(T)).TableInfo.PrimaryKey, primaryKey); - return Single(string.Format("WHERE {0}", BuildPrimaryKeySql(primaryKeyValuePairs, ref index)), primaryKeyValuePairs.Select(x => x.Value).ToArray()); - } - public T SingleOrDefault(object primaryKey) - { - var index = 0; - var primaryKeyValuePairs = GetPrimaryKeyValues(PocoData.ForType(typeof(T)).TableInfo.PrimaryKey, primaryKey); - return SingleOrDefault(string.Format("WHERE {0}", BuildPrimaryKeySql(primaryKeyValuePairs, ref index)), primaryKeyValuePairs.Select(x => x.Value).ToArray()); - } - public T Single(string sql, params object[] args) - { - return Query(sql, args).Single(); - } - public T SingleOrDefault(string sql, params object[] args) - { - return Query(sql, args).SingleOrDefault(); - } - public T First(string sql, params object[] args) - { - return Query(sql, args).First(); - } - public T FirstOrDefault(string sql, params object[] args) - { - return Query(sql, args).FirstOrDefault(); - } - public T Single(Sql sql) - { - return Query(sql).Single(); - } - public T SingleOrDefault(Sql sql) - { - return Query(sql).SingleOrDefault(); - } - public T First(Sql sql) - { - return Query(sql).First(); - } - public T FirstOrDefault(Sql sql) - { - return Query(sql).FirstOrDefault(); - } - - public string EscapeTableName(string str) - { - // Assume table names with "dot" are already escaped - return str.IndexOf('.') >= 0 ? str : EscapeSqlIdentifier(str); - } - - public string EscapeSqlIdentifier(string str) - { - switch (_dbType) - { - case DBType.MySql: - return string.Format("`{0}`", str); - - case DBType.PostgreSQL: - return string.Format("\"{0}\"", str); - - case DBType.Oracle: - return string.Format("\"{0}\"", str.ToUpperInvariant()); - - default: - return string.Format("[{0}]", str); - } - } - - public object Insert(string tableName, string primaryKeyName, object poco) - { - return Insert(tableName, primaryKeyName, true, poco); - } - - // Insert a poco into a table. If the poco has a property with the same name - // as the primary key the id of the new record is assigned to it. Either way, - // the new id is returned. - public object Insert(string tableName, string primaryKeyName, bool autoIncrement, object poco) - { - try - { - OpenSharedConnection(); - try - { - using (var cmd = CreateCommand(_sharedConnection, "")) - { - var pd = PocoData.ForObject(poco, primaryKeyName); - var names = new List(); - var values = new List(); - var index = 0; - var versionName = ""; - - foreach (var i in pd.Columns) - { - // Don't insert result columns - if (i.Value.ResultColumn) - continue; - - // Don't insert the primary key (except under oracle where we need bring in the next sequence value) - if (autoIncrement && primaryKeyName != null && string.Compare(i.Key, primaryKeyName, true) == 0) - { - if (_dbType == DBType.Oracle && !string.IsNullOrEmpty(pd.TableInfo.SequenceName)) - { - names.Add(i.Key); - values.Add(string.Format("{0}.nextval", pd.TableInfo.SequenceName)); - } - continue; - } - - names.Add(EscapeSqlIdentifier(i.Key)); - values.Add(string.Format("{0}{1}", _paramPrefix, index++)); - - object val = i.Value.GetValue(poco); - if (i.Value.VersionColumn) - { - val = 1; - versionName = i.Key; - } - - AddParam(cmd, val, _paramPrefix); - } - - cmd.CommandText = string.Format("INSERT INTO {0} ({1}) VALUES ({2})", - EscapeTableName(tableName), - string.Join(",", names.ToArray()), - string.Join(",", values.ToArray()) - ); - - object id; - - if (!autoIncrement) - { - DoPreExecute(cmd); - cmd.ExecuteNonQuery(); - OnExecutedCommand(cmd); - id = true; - } - else - { - - switch (_dbType) - { - case DBType.SqlServerCE: - DoPreExecute(cmd); - cmd.ExecuteNonQuery(); - OnExecutedCommand(cmd); - id = ExecuteScalar("SELECT @@@IDENTITY AS NewID;"); - break; - case DBType.SqlServer: - cmd.CommandText += ";\nSELECT SCOPE_IDENTITY() AS NewID;"; - DoPreExecute(cmd); - id = cmd.ExecuteScalar(); - OnExecutedCommand(cmd); - break; - case DBType.PostgreSQL: - if (primaryKeyName != null) - { - cmd.CommandText += string.Format("returning {0} as NewID", EscapeSqlIdentifier(primaryKeyName)); - DoPreExecute(cmd); - id = cmd.ExecuteScalar(); - } - else - { - id = -1; - DoPreExecute(cmd); - cmd.ExecuteNonQuery(); - } - OnExecutedCommand(cmd); - break; - case DBType.Oracle: - if (primaryKeyName != null) - { - cmd.CommandText += string.Format(" returning {0} into :newid", EscapeSqlIdentifier(primaryKeyName)); - var param = cmd.CreateParameter(); - param.ParameterName = ":newid"; - param.Value = DBNull.Value; - param.Direction = ParameterDirection.ReturnValue; - param.DbType = DbType.Int64; - cmd.Parameters.Add(param); - DoPreExecute(cmd); - cmd.ExecuteNonQuery(); - id = param.Value; - } - else - { - id = -1; - DoPreExecute(cmd); - cmd.ExecuteNonQuery(); - } - OnExecutedCommand(cmd); - break; - case DBType.SQLite: - if (primaryKeyName != null) - { - cmd.CommandText += ";\nSELECT last_insert_rowid();"; - DoPreExecute(cmd); - id = cmd.ExecuteScalar(); - } - else - { - id = -1; - DoPreExecute(cmd); - cmd.ExecuteNonQuery(); - } - OnExecutedCommand(cmd); - break; - default: - cmd.CommandText += ";\nSELECT @@IDENTITY AS NewID;"; - DoPreExecute(cmd); - id = cmd.ExecuteScalar(); - OnExecutedCommand(cmd); - break; - } - - // Assign the ID back to the primary key property - if (primaryKeyName != null) - { - PocoColumn pc; - if (pd.Columns.TryGetValue(primaryKeyName, out pc)) - { - pc.SetValue(poco, pc.ChangeType(id)); - } - } - } - - // Assign the Version column - if (!string.IsNullOrEmpty(versionName)) - { - PocoColumn pc; - if (pd.Columns.TryGetValue(versionName, out pc)) - { - pc.SetValue(poco, pc.ChangeType(1)); - } - } - - return id; - } - } - finally - { - CloseSharedConnection(); - } - } - catch (Exception x) - { - OnException(x); - throw; - } - } - - // Insert an annotated poco object - public object Insert(object poco) - { - var pd = PocoData.ForType(poco.GetType()); - return Insert(pd.TableInfo.TableName, pd.TableInfo.PrimaryKey, pd.TableInfo.AutoIncrement, poco); - } - - public void InsertMany(IEnumerable pocoList) - { - using (var tran = GetTransaction()) - { - foreach (var poco in pocoList) - { - Insert(poco); - } - - tran.Complete(); - } - } - - public int Update(string tableName, string primaryKeyName, object poco, object primaryKeyValue) - { - return Update(tableName, primaryKeyName, poco, primaryKeyValue, null); - } - - - // Update a record with values from a poco. primary key value can be either supplied or read from the poco - public int Update(string tableName, string primaryKeyName, object poco, object primaryKeyValue, IEnumerable columns) - { - try - { - OpenSharedConnection(); - try - { - using (var cmd = CreateCommand(_sharedConnection, "")) - { - var sb = new StringBuilder(); - var index = 0; - var pd = PocoData.ForObject(poco, primaryKeyName); - string versionName = null; - object versionValue = null; - - var primaryKeyValuePairs = GetPrimaryKeyValues(primaryKeyName, primaryKeyValue); - - foreach (var i in pd.Columns) - { - // Don't update the primary key, but grab the value if we don't have it - if (primaryKeyValue == null && primaryKeyValuePairs.ContainsKey(i.Key)) - { - primaryKeyValuePairs[i.Key] = i.Value.PropertyInfo.GetValue(poco, null); - continue; - } - - // Dont update result only columns - if (i.Value.ResultColumn) - continue; - - if (!i.Value.VersionColumn && columns != null && !columns.Contains(i.Value.ColumnName, StringComparer.OrdinalIgnoreCase)) - continue; - - object value = i.Value.PropertyInfo.GetValue(poco, null); - - if (i.Value.VersionColumn) - { - versionName = i.Key; - versionValue = value; - value = Convert.ToInt64(value) + 1; - } - - // Build the sql - if (index > 0) - sb.Append(", "); - sb.AppendFormat("{0} = {1}{2}", EscapeSqlIdentifier(i.Key), _paramPrefix, index++); - - // Store the parameter in the command - AddParam(cmd, value, _paramPrefix); - } - - - cmd.CommandText = string.Format("UPDATE {0} SET {1} WHERE {2}", - EscapeTableName(tableName), sb.ToString(), BuildPrimaryKeySql(primaryKeyValuePairs, ref index)); - - foreach (var keyValue in primaryKeyValuePairs) - { - AddParam(cmd, keyValue.Value, _paramPrefix); - } - - if (!string.IsNullOrEmpty(versionName)) - { - cmd.CommandText += string.Format(" AND {0} = {1}{2}", EscapeSqlIdentifier(versionName), _paramPrefix, index++); - AddParam(cmd, versionValue, _paramPrefix); - } - - DoPreExecute(cmd); - - // Do it - var result = cmd.ExecuteNonQuery(); - OnExecutedCommand(cmd); - - // Set Version - if (!string.IsNullOrEmpty(versionName)) - { - PocoColumn pc; - if (pd.Columns.TryGetValue(versionName, out pc)) - { - pc.PropertyInfo.SetValue(poco, Convert.ChangeType(Convert.ToInt64(versionValue) + 1, pc.PropertyInfo.PropertyType), null); - } - } - - return result; - } - } - finally - { - CloseSharedConnection(); - } - } - catch (Exception x) - { - OnException(x); - throw; - } - } - - private string BuildPrimaryKeySql(Dictionary primaryKeyValuePair, ref int index) - { - var tempIndex = index; - index += primaryKeyValuePair.Count; - return string.Join(" AND ", primaryKeyValuePair.Select((x, i) => string.Format("{0} = {1}{2}", EscapeSqlIdentifier(x.Key), _paramPrefix, tempIndex + i)).ToArray()); - } - - private Dictionary GetPrimaryKeyValues(string primaryKeyName, object primaryKeyValue) - { - Dictionary primaryKeyValues; - - var multiplePrimaryKeysNames = primaryKeyName.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToArray(); - if (primaryKeyValue != null) - { - if (multiplePrimaryKeysNames.Length == 1) - primaryKeyValues = new Dictionary(StringComparer.OrdinalIgnoreCase) { { primaryKeyName, primaryKeyValue } }; - else - primaryKeyValues = multiplePrimaryKeysNames.ToDictionary(x => x, - x => primaryKeyValue.GetType().GetProperties() - .Where(y => string.Equals(x, y.Name, StringComparison.OrdinalIgnoreCase)) - .Single().GetValue(primaryKeyValue, null), StringComparer.OrdinalIgnoreCase); - } - else - { - primaryKeyValues = multiplePrimaryKeysNames.ToDictionary(x => x, x => (object)null, StringComparer.OrdinalIgnoreCase); - } - return primaryKeyValues; - } - - public int Update(string tableName, string primaryKeyName, object poco) - { - return Update(tableName, primaryKeyName, poco, null); - } - - public int Update(string tableName, string primaryKeyName, object poco, IEnumerable columns) - { - return Update(tableName, primaryKeyName, poco, null, columns); - } - - public int Update(object poco, IEnumerable columns) - { - return Update(poco, null, columns); - } - - public int Update(object poco) - { - return Update(poco, null, null); - } - - public int Update(object poco, object primaryKeyValue) - { - return Update(poco, primaryKeyValue, null); - } - public int Update(object poco, object primaryKeyValue, IEnumerable columns) - { - var pd = PocoData.ForType(poco.GetType()); - return Update(pd.TableInfo.TableName, pd.TableInfo.PrimaryKey, poco, primaryKeyValue, columns); - } - - public int Update(string sql, params object[] args) - { - var pd = PocoData.ForType(typeof(T)); - return Execute(string.Format("UPDATE {0} {1}", EscapeTableName(pd.TableInfo.TableName), sql), args); - } - - public int Update(Sql sql) - { - var pd = PocoData.ForType(typeof(T)); - return Execute(new Sql(string.Format("UPDATE {0}", EscapeTableName(pd.TableInfo.TableName))).Append(sql)); - } - - public void UpdateMany(IEnumerable pocoList) - { - using (var tran = GetTransaction()) - { - foreach (var poco in pocoList) - { - Update(poco); - } - - tran.Complete(); - } - } - - - public int Delete(string tableName, string primaryKeyName, object poco) - { - return Delete(tableName, primaryKeyName, poco, null); - } - - public int Delete(string tableName, string primaryKeyName, object poco, object primaryKeyValue) - { - var primaryKeyValuePairs = GetPrimaryKeyValues(primaryKeyName, primaryKeyValue); - // If primary key value not specified, pick it up from the object - if (primaryKeyValue == null) - { - var pd = PocoData.ForObject(poco, primaryKeyName); - foreach (var i in pd.Columns) - { - if (primaryKeyValuePairs.ContainsKey(i.Key)) - { - primaryKeyValuePairs[i.Key] = i.Value.PropertyInfo.GetValue(poco, null); - } - } - } - - // Do it - var index = 0; - var sql = string.Format("DELETE FROM {0} WHERE {1}", tableName, BuildPrimaryKeySql(primaryKeyValuePairs, ref index)); - return Execute(sql, primaryKeyValuePairs.Select(x => x.Value).ToArray()); - } - - public int Delete(object poco) - { - var pd = PocoData.ForType(poco.GetType()); - return Delete(pd.TableInfo.TableName, pd.TableInfo.PrimaryKey, poco); - } - - public int Delete(object pocoOrPrimaryKey) - { - if (pocoOrPrimaryKey.GetType() == typeof(T)) - return Delete(pocoOrPrimaryKey); - var pd = PocoData.ForType(typeof(T)); - return Delete(pd.TableInfo.TableName, pd.TableInfo.PrimaryKey, null, pocoOrPrimaryKey); - } - - public int Delete(string sql, params object[] args) - { - var pd = PocoData.ForType(typeof(T)); - return Execute(string.Format("DELETE FROM {0} {1}", EscapeTableName(pd.TableInfo.TableName), sql), args); - } - - public int Delete(Sql sql) - { - var pd = PocoData.ForType(typeof(T)); - return Execute(new Sql(string.Format("DELETE FROM {0}", EscapeTableName(pd.TableInfo.TableName))).Append(sql)); - } - - // Check if a poco represents a new record - public bool IsNew(string primaryKeyName, object poco) - { - var pd = PocoData.ForObject(poco, primaryKeyName); - object pk; - PocoColumn pc; - if (pd.Columns.TryGetValue(primaryKeyName, out pc)) - { - pk = pc.GetValue(poco); - } -#if !PETAPOCO_NO_DYNAMIC - else if (poco.GetType() == typeof(System.Dynamic.ExpandoObject)) - { - return true; - } -#endif - else - { - var pi = poco.GetType().GetProperty(primaryKeyName); - if (pi == null) - throw new ArgumentException(string.Format("The object doesn't have a property matching the primary key column name '{0}'", primaryKeyName)); - pk = pi.GetValue(poco, null); - } - - if (pk == null) - return true; - - var type = pk.GetType(); - - if (type.IsValueType) - { - // Common primary key types - if (type == typeof(long)) - return (long)pk == 0; - else if (type == typeof(ulong)) - return (ulong)pk == 0; - else if (type == typeof(int)) - return (int)pk == 0; - else if (type == typeof(uint)) - return (uint)pk == 0; - - // Create a default instance and compare - return pk == Activator.CreateInstance(pk.GetType()); - } - else - { - return pk == null; - } - } - - public bool IsNew(object poco) - { - var pd = PocoData.ForType(poco.GetType()); - if (!pd.TableInfo.AutoIncrement) - throw new InvalidOperationException("IsNew() and Save() are only supported on tables with auto-increment/identity primary key columns"); - return IsNew(pd.TableInfo.PrimaryKey, poco); - } - - // Insert new record or Update existing record - public void Save(string tableName, string primaryKeyName, object poco) - { - if (IsNew(primaryKeyName, poco)) - { - Insert(tableName, primaryKeyName, true, poco); - } - else - { - Update(tableName, primaryKeyName, poco); - } - } - - public void Save(object poco) - { - var pd = PocoData.ForType(poco.GetType()); - Save(pd.TableInfo.TableName, pd.TableInfo.PrimaryKey, poco); - } - - public void SaveMany(IEnumerable pocoList) - { - using (var tran = GetTransaction()) - { - foreach (var poco in pocoList) - { - Save(poco); - } - - tran.Complete(); - } - } - - public int CommandTimeout { get; set; } - public int OneTimeCommandTimeout { get; set; } - - void DoPreExecute(IDbCommand cmd) - { - // Setup command timeout - if (OneTimeCommandTimeout != 0) - { - cmd.CommandTimeout = OneTimeCommandTimeout; - OneTimeCommandTimeout = 0; - } - else if (CommandTimeout != 0) - { - cmd.CommandTimeout = CommandTimeout; - } - - // Call hook - OnExecutingCommand(cmd); - - // Save it - _lastSql = cmd.CommandText; - _lastArgs = (from IDataParameter parameter in cmd.Parameters select parameter.Value).ToArray(); - } - - public string LastSQL { get { return _lastSql; } } - public object[] LastArgs { get { return _lastArgs; } } - public string LastCommand - { - get { return FormatCommand(_lastSql, _lastArgs); } - } - - public string FormatCommand(IDbCommand cmd) - { - return FormatCommand(cmd.CommandText, (from IDataParameter parameter in cmd.Parameters select parameter.Value).ToArray()); - } - - public string FormatCommand(string sql, object[] args) - { - var sb = new StringBuilder(); - if (sql == null) - return ""; - sb.Append(sql); - if (args != null && args.Length > 0) - { - sb.Append("\n"); - for (int i = 0; i < args.Length; i++) - { - sb.AppendFormat("\t -> {0}{1} [{2}] = \"{3}\"\n", _paramPrefix, i, args[i].GetType().Name, args[i]); - } - sb.Remove(sb.Length - 1, 1); - } - return sb.ToString(); - } - - - public static IMapper Mapper - { - get; - set; - } - - public class PocoColumn - { - public string ColumnName; - public PropertyInfo PropertyInfo; - public bool ResultColumn; - public bool VersionColumn; - public virtual void SetValue(object target, object val) { PropertyInfo.SetValue(target, val, null); } - public virtual object GetValue(object target) { return PropertyInfo.GetValue(target, null); } - public virtual object ChangeType(object val) { return Convert.ChangeType(val, PropertyInfo.PropertyType); } - } - public class ExpandoColumn : PocoColumn - { - public override void SetValue(object target, object val) { (target as IDictionary)[ColumnName] = val; } - public override object GetValue(object target) - { - object val = null; - (target as IDictionary).TryGetValue(ColumnName, out val); - return val; - } - public override object ChangeType(object val) { return val; } - } - public class PocoData - { - public static PocoData ForObject(object o, string primaryKeyName) - { - var t = o.GetType(); -#if !PETAPOCO_NO_DYNAMIC - if (t == typeof(System.Dynamic.ExpandoObject)) - { - var pd = new PocoData(); - pd.TableInfo = new TableInfo(); - pd.Columns = new Dictionary(StringComparer.OrdinalIgnoreCase); - pd.Columns.Add(primaryKeyName, new ExpandoColumn() { ColumnName = primaryKeyName }); - pd.TableInfo.PrimaryKey = primaryKeyName; - pd.TableInfo.AutoIncrement = true; - foreach (var col in (o as IDictionary).Keys) - { - if (col != primaryKeyName) - pd.Columns.Add(col, new ExpandoColumn() { ColumnName = col }); - } - return pd; - } - else -#endif - return ForType(t); - } - static System.Threading.ReaderWriterLockSlim RWLock = new System.Threading.ReaderWriterLockSlim(); - public static PocoData ForType(Type t) - { -#if !PETAPOCO_NO_DYNAMIC - if (t == typeof(System.Dynamic.ExpandoObject)) - throw new InvalidOperationException("Can't use dynamic types with this method"); -#endif - // Check cache - RWLock.EnterReadLock(); - PocoData pd; - try - { - if (m_PocoDatas.TryGetValue(t, out pd)) - return pd; - } - finally - { - RWLock.ExitReadLock(); - } - - - // Cache it - RWLock.EnterWriteLock(); - try - { - // Check again - if (m_PocoDatas.TryGetValue(t, out pd)) - return pd; - - // Create it - pd = new PocoData(t); - m_PocoDatas.Add(t, pd); - } - finally - { - RWLock.ExitWriteLock(); - } - - return pd; - } - - public PocoData() - { - } - - public PocoData(Type t) - { - type = t; - TableInfo = new TableInfo(); - - // Get the table name - var a = t.GetCustomAttributes(typeof(TableNameAttribute), true); - TableInfo.TableName = a.Length == 0 ? t.Name : (a[0] as TableNameAttribute).Value; - - // Get the primary key - a = t.GetCustomAttributes(typeof(PrimaryKeyAttribute), true); - TableInfo.PrimaryKey = a.Length == 0 ? "ID" : (a[0] as PrimaryKeyAttribute).Value; - TableInfo.SequenceName = a.Length == 0 ? null : (a[0] as PrimaryKeyAttribute).sequenceName; - TableInfo.AutoIncrement = a.Length == 0 ? false : (a[0] as PrimaryKeyAttribute).autoIncrement; - - // Set autoincrement false if primary key has multiple columns - TableInfo.AutoIncrement = TableInfo.AutoIncrement ? !TableInfo.PrimaryKey.Contains(',') : TableInfo.AutoIncrement; - - // Call column mapper - if (Database.Mapper != null) - Database.Mapper.GetTableInfo(t, TableInfo); - - // Work out bound properties - bool ExplicitColumns = t.GetCustomAttributes(typeof(ExplicitColumnsAttribute), true).Length > 0; - Columns = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (var pi in t.GetProperties()) - { - // Work out if properties is to be included - var ColAttrs = pi.GetCustomAttributes(typeof(ColumnAttribute), true); - if (ExplicitColumns) - { - if (ColAttrs.Length == 0) - continue; - } - else - { - if (pi.GetCustomAttributes(typeof(IgnoreAttribute), true).Length != 0) - continue; - } - - var pc = new PocoColumn(); - pc.PropertyInfo = pi; - - // Work out the DB column name - if (ColAttrs.Length > 0) - { - var colattr = (ColumnAttribute)ColAttrs[0]; - pc.ColumnName = colattr.Name; - if ((colattr as ResultColumnAttribute) != null) - pc.ResultColumn = true; - if ((colattr as VersionColumnAttribute) != null) - pc.VersionColumn = true; - } - if (pc.ColumnName == null) - { - pc.ColumnName = pi.Name; - if (Database.Mapper != null && !Database.Mapper.MapPropertyToColumn(pi, ref pc.ColumnName, ref pc.ResultColumn)) - continue; - } - - // Store it - Columns.Add(pc.ColumnName, pc); - } - - // Build column list for automatic select - QueryColumns = (from c in Columns where !c.Value.ResultColumn select c.Key).ToArray(); - - } - - static bool IsIntegralType(Type t) - { - var tc = Type.GetTypeCode(t); - return tc >= TypeCode.SByte && tc <= TypeCode.UInt64; - } - - // Create factory function that can convert a IDataReader record into a POCO - public Delegate GetFactory(string sql, string connString, bool ForceDateTimesToUtc, int firstColumn, int countColumns, IDataReader r) - { - // Check cache - var key = string.Format("{0}:{1}:{2}:{3}:{4}", sql, connString, ForceDateTimesToUtc, firstColumn, countColumns); - RWLock.EnterReadLock(); - try - { - // Have we already created it? - Delegate factory; - if (PocoFactories.TryGetValue(key, out factory)) - return factory; - } - finally - { - RWLock.ExitReadLock(); - } - - // Take the writer lock - RWLock.EnterWriteLock(); - - try - { - - // Check again, just in case - Delegate factory; - if (PocoFactories.TryGetValue(key, out factory)) - return factory; - - // Create the method - var m = new DynamicMethod("petapoco_factory_" + PocoFactories.Count.ToString(), type, new Type[] { typeof(IDataReader) }, true); - var il = m.GetILGenerator(); - -#if !PETAPOCO_NO_DYNAMIC - if (type == typeof(object)) - { - // var poco=new T() - il.Emit(OpCodes.Newobj, typeof(System.Dynamic.ExpandoObject).GetConstructor(Type.EmptyTypes)); // obj - - MethodInfo fnAdd = typeof(IDictionary).GetMethod("Add"); - - // Enumerate all fields generating a set assignment for the column - for (int i = firstColumn; i < firstColumn + countColumns; i++) - { - var srcType = r.GetFieldType(i); - - il.Emit(OpCodes.Dup); // obj, obj - il.Emit(OpCodes.Ldstr, r.GetName(i)); // obj, obj, fieldname - - // Get the converter - Func converter = null; - if (Database.Mapper != null) - converter = Database.Mapper.GetFromDbConverter(null, srcType); - if (ForceDateTimesToUtc && converter == null && srcType == typeof(DateTime)) - converter = delegate(object src) { return new DateTime(((DateTime)src).Ticks, DateTimeKind.Utc); }; - - // Setup stack for call to converter - AddConverterToStack(il, converter); - - // r[i] - il.Emit(OpCodes.Ldarg_0); // obj, obj, fieldname, converter?, rdr - il.Emit(OpCodes.Ldc_I4, i); // obj, obj, fieldname, converter?, rdr,i - il.Emit(OpCodes.Callvirt, fnGetValue); // obj, obj, fieldname, converter?, value - - // Convert DBNull to null - il.Emit(OpCodes.Dup); // obj, obj, fieldname, converter?, value, value - il.Emit(OpCodes.Isinst, typeof(DBNull)); // obj, obj, fieldname, converter?, value, (value or null) - var lblNotNull = il.DefineLabel(); - il.Emit(OpCodes.Brfalse_S, lblNotNull); // obj, obj, fieldname, converter?, value - il.Emit(OpCodes.Pop); // obj, obj, fieldname, converter? - if (converter != null) - il.Emit(OpCodes.Pop); // obj, obj, fieldname, - il.Emit(OpCodes.Ldnull); // obj, obj, fieldname, null - if (converter != null) - { - var lblReady = il.DefineLabel(); - il.Emit(OpCodes.Br_S, lblReady); - il.MarkLabel(lblNotNull); - il.Emit(OpCodes.Callvirt, fnInvoke); - il.MarkLabel(lblReady); - } - else - { - il.MarkLabel(lblNotNull); - } - - il.Emit(OpCodes.Callvirt, fnAdd); - } - } - else -#endif - if (type.IsValueType || type == typeof(string) || type == typeof(byte[])) - { - // Do we need to install a converter? - var srcType = r.GetFieldType(0); - var converter = GetConverter(ForceDateTimesToUtc, null, srcType, type); - - // "if (!rdr.IsDBNull(i))" - il.Emit(OpCodes.Ldarg_0); // rdr - il.Emit(OpCodes.Ldc_I4_0); // rdr,0 - il.Emit(OpCodes.Callvirt, fnIsDBNull); // bool - var lblCont = il.DefineLabel(); - il.Emit(OpCodes.Brfalse_S, lblCont); - il.Emit(OpCodes.Ldnull); // null - var lblFin = il.DefineLabel(); - il.Emit(OpCodes.Br_S, lblFin); - - il.MarkLabel(lblCont); - - // Setup stack for call to converter - AddConverterToStack(il, converter); - - il.Emit(OpCodes.Ldarg_0); // rdr - il.Emit(OpCodes.Ldc_I4_0); // rdr,0 - il.Emit(OpCodes.Callvirt, fnGetValue); // value - - // Call the converter - if (converter != null) - il.Emit(OpCodes.Callvirt, fnInvoke); - - il.MarkLabel(lblFin); - il.Emit(OpCodes.Unbox_Any, type); // value converted - } - else if (type == typeof(Dictionary)) - { - Func> func = reader => - { - var dict = new Dictionary(StringComparer.OrdinalIgnoreCase); - for (int i = firstColumn; i < firstColumn + countColumns; i++) - { - var value = reader.IsDBNull(i) ? null : reader.GetValue(i); - var name = reader.GetName(i); - if (!dict.ContainsKey(name)) - dict.Add(name, value); - } - return dict; - }; - - var localDel = Delegate.CreateDelegate(typeof(Func>), func.Target, func.Method); - PocoFactories.Add(key, localDel); - return localDel; - } - else - { - // var poco=new T() - il.Emit(OpCodes.Newobj, type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null)); - - // Enumerate all fields generating a set assignment for the column - for (int i = firstColumn; i < firstColumn + countColumns; i++) - { - // Get the PocoColumn for this db column, ignore if not known - PocoColumn pc; - if (!Columns.TryGetValue(r.GetName(i), out pc) && !Columns.TryGetValue(r.GetName(i).Replace("_", ""), out pc)) - { - continue; - } - - // Get the source type for this column - var srcType = r.GetFieldType(i); - var dstType = pc.PropertyInfo.PropertyType; - - // "if (!rdr.IsDBNull(i))" - il.Emit(OpCodes.Ldarg_0); // poco,rdr - il.Emit(OpCodes.Ldc_I4, i); // poco,rdr,i - il.Emit(OpCodes.Callvirt, fnIsDBNull); // poco,bool - var lblNext = il.DefineLabel(); - il.Emit(OpCodes.Brtrue_S, lblNext); // poco - - il.Emit(OpCodes.Dup); // poco,poco - - // Do we need to install a converter? - var converter = GetConverter(ForceDateTimesToUtc, pc, srcType, dstType); - - // Fast - bool Handled = false; - if (converter == null) - { - var valuegetter = typeof(IDataRecord).GetMethod("Get" + srcType.Name, new Type[] { typeof(int) }); - if (valuegetter != null - && valuegetter.ReturnType == srcType - && (valuegetter.ReturnType == dstType || valuegetter.ReturnType == Nullable.GetUnderlyingType(dstType))) - { - il.Emit(OpCodes.Ldarg_0); // *,rdr - il.Emit(OpCodes.Ldc_I4, i); // *,rdr,i - il.Emit(OpCodes.Callvirt, valuegetter); // *,value - - // Convert to Nullable - if (Nullable.GetUnderlyingType(dstType) != null) - { - il.Emit(OpCodes.Newobj, dstType.GetConstructor(new Type[] { Nullable.GetUnderlyingType(dstType) })); - } - - il.Emit(OpCodes.Callvirt, pc.PropertyInfo.GetSetMethod(true)); // poco - Handled = true; - } - } - - // Not so fast - if (!Handled) - { - // Setup stack for call to converter - AddConverterToStack(il, converter); - - // "value = rdr.GetValue(i)" - il.Emit(OpCodes.Ldarg_0); // *,rdr - il.Emit(OpCodes.Ldc_I4, i); // *,rdr,i - il.Emit(OpCodes.Callvirt, fnGetValue); // *,value - - // Call the converter - if (converter != null) - il.Emit(OpCodes.Callvirt, fnInvoke); - - // Assign it - il.Emit(OpCodes.Unbox_Any, pc.PropertyInfo.PropertyType); // poco,poco,value - il.Emit(OpCodes.Callvirt, pc.PropertyInfo.GetSetMethod(true)); // poco - } - - il.MarkLabel(lblNext); - } - - var fnOnLoaded = RecurseInheritedTypes(type, (x) => x.GetMethod("OnLoaded", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null)); - if (fnOnLoaded != null) - { - il.Emit(OpCodes.Dup); - il.Emit(OpCodes.Callvirt, fnOnLoaded); - } - } - - il.Emit(OpCodes.Ret); - - // Cache it, return it - var del = m.CreateDelegate(Expression.GetFuncType(typeof(IDataReader), type)); - PocoFactories.Add(key, del); - return del; - } - finally - { - RWLock.ExitWriteLock(); - } - } - - private static void AddConverterToStack(ILGenerator il, Func converter) - { - if (converter != null) - { - // Add the converter - int converterIndex = m_Converters.Count; - m_Converters.Add(converter); - - // Generate IL to push the converter onto the stack - il.Emit(OpCodes.Ldsfld, fldConverters); - il.Emit(OpCodes.Ldc_I4, converterIndex); - il.Emit(OpCodes.Callvirt, fnListGetItem); // Converter - } - } - - public static Func GetConverter(bool forceDateTimesToUtc, PocoColumn pc, Type srcType, Type dstType) - { - Func converter = null; - - // Get converter from the mapper - if (Database.Mapper != null) - { - if (pc != null) - { - converter = Database.Mapper.GetFromDbConverter(pc.PropertyInfo, srcType); - } - else - { - var m2 = Database.Mapper as IMapper2; - if (m2 != null) - { - converter = m2.GetFromDbConverter(dstType, srcType); - } - } - } - - // Standard DateTime->Utc mapper - if (forceDateTimesToUtc && converter == null && srcType == typeof(DateTime) && (dstType == typeof(DateTime) || dstType == typeof(DateTime?))) - { - converter = delegate(object src) { return new DateTime(((DateTime)src).Ticks, DateTimeKind.Utc); }; - } - - // Forced type conversion including integral types -> enum - if (converter == null) - { - if (dstType.IsEnum && IsIntegralType(srcType)) - { - if (srcType != typeof(int)) - { - converter = delegate(object src) { return Convert.ChangeType(src, typeof(int), null); }; - } - } - else if (!dstType.IsAssignableFrom(srcType)) - { - converter = delegate(object src) { return Convert.ChangeType(src, dstType, null); }; - } - } - return converter; - } - - - static T RecurseInheritedTypes(Type t, Func cb) - { - while (t != null) - { - T info = cb(t); - if (info != null) - return info; - t = t.BaseType; - } - return default(T); - } - - - static Dictionary m_PocoDatas = new Dictionary(); - static List> m_Converters = new List>(); - static MethodInfo fnGetValue = typeof(IDataRecord).GetMethod("GetValue", new Type[] { typeof(int) }); - static MethodInfo fnIsDBNull = typeof(IDataRecord).GetMethod("IsDBNull"); - static FieldInfo fldConverters = typeof(PocoData).GetField("m_Converters", BindingFlags.Static | BindingFlags.GetField | BindingFlags.NonPublic); - static MethodInfo fnListGetItem = typeof(List>).GetProperty("Item").GetGetMethod(); - static MethodInfo fnInvoke = typeof(Func).GetMethod("Invoke"); - public Type type; - public string[] QueryColumns { get; private set; } - public TableInfo TableInfo { get; private set; } - public Dictionary Columns { get; private set; } - Dictionary PocoFactories = new Dictionary(); - } - - // Member variables - string _connectionString; - string _providerName; - DbProviderFactory _factory; - IDbConnection _sharedConnection; - IDbTransaction _transaction; - bool _transactionCancelled; - string _lastSql; - object[] _lastArgs; - string _paramPrefix = "@"; - } - - // Transaction object helps maintain transaction depth counts - public interface ITransaction : IDisposable - { - void Complete(); - } - - public class Transaction : ITransaction - { - public Transaction(Database db) : this(db, null) { } - - public Transaction(Database db, IsolationLevel? isolationLevel) - { - _db = db; - _db.BeginTransaction(isolationLevel); - } - - public virtual void Complete() - { - _db.CompleteTransaction(); - _db = null; - } - - public void Dispose() - { - if (_db != null) - _db.AbortTransaction(); - } - - Database _db; - } - - // Simple helper class for building SQL statments - public class Sql - { - public Sql() - { - } - - public Sql(string sql, params object[] args) - { - _sql = sql; - _args = args; - } - - public static Sql Builder - { - get { return new Sql(); } - } - - string _sql; - object[] _args; - Sql _rhs; - string _sqlFinal; - object[] _argsFinal; - - private void Build() - { - // already built? - if (_sqlFinal != null) - return; - - // Build it - var sb = new StringBuilder(); - var args = new List(); - Build(sb, args, null); - _sqlFinal = sb.ToString(); - _argsFinal = args.ToArray(); - } - - public string SQL - { - get - { - Build(); - return _sqlFinal; - } - } - - public object[] Arguments - { - get - { - Build(); - return _argsFinal; - } - } - - public Sql Append(Sql sql) - { - if (_rhs != null) - _rhs.Append(sql); - else - _rhs = sql; - - return this; - } - - public Sql Append(string sql, params object[] args) - { - return Append(new Sql(sql, args)); - } - - static bool Is(Sql sql, string sqltype) - { - return sql != null && sql._sql != null && sql._sql.StartsWith(sqltype, StringComparison.InvariantCultureIgnoreCase); - } - - private void Build(StringBuilder sb, List args, Sql lhs) - { - if (!String.IsNullOrEmpty(_sql)) - { - // Add SQL to the string - if (sb.Length > 0) - { - sb.Append("\n"); - } - - var sql = Database.ProcessParams(_sql, _args, args); - - if (Is(lhs, "WHERE ") && Is(this, "WHERE ")) - sql = "AND " + sql.Substring(6); - if (Is(lhs, "ORDER BY ") && Is(this, "ORDER BY ")) - sql = ", " + sql.Substring(9); - - sb.Append(sql); - } - - // Now do rhs - if (_rhs != null) - _rhs.Build(sb, args, this); - } - - public Sql Where(string sql, params object[] args) - { - return Append(new Sql("WHERE (" + sql + ")", args)); - } - - public Sql OrderBy(params object[] columns) - { - return Append(new Sql("ORDER BY " + String.Join(", ", (from x in columns select x.ToString()).ToArray()))); - } - - public Sql Select(params object[] columns) - { - return Append(new Sql("SELECT " + String.Join(", ", (from x in columns select x.ToString()).ToArray()))); - } - - public Sql From(params object[] tables) - { - return Append(new Sql("FROM " + String.Join(", ", (from x in tables select x.ToString()).ToArray()))); - } - - public Sql GroupBy(params object[] columns) - { - return Append(new Sql("GROUP BY " + String.Join(", ", (from x in columns select x.ToString()).ToArray()))); - } - - private SqlJoinClause Join(string JoinType, string table) - { - return new SqlJoinClause(Append(new Sql(JoinType + table))); - } - - public SqlJoinClause InnerJoin(string table) { return Join("INNER JOIN ", table); } - public SqlJoinClause LeftJoin(string table) { return Join("LEFT JOIN ", table); } - - public class SqlJoinClause - { - private readonly Sql _sql; - - public SqlJoinClause(Sql sql) - { - _sql = sql; - } - - public Sql On(string onClause, params object[] args) - { - return _sql.Append("ON " + onClause, args); - } - } - } - -} \ No newline at end of file diff --git a/NzbDrone.Core/Datastore/SqlCeProxy.cs b/NzbDrone.Core/Datastore/SqlCeProxy.cs deleted file mode 100644 index 99c2f8ccc..000000000 --- a/NzbDrone.Core/Datastore/SqlCeProxy.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using System.Data.Common; -using System.Linq; -using System.Reflection; - -namespace NzbDrone.Core.Datastore -{ - public static class SqlCeProxy - { - private static readonly object instance; - private static readonly Type proxyType; - - static SqlCeProxy() - { - proxyType = Assembly.Load("NzbDrone.SqlCe").GetExportedTypes()[0]; - instance = Activator.CreateInstance(proxyType); - } - - public static DbConnection EnsureDatabase(string connectionString) - { - var factoryMethod = proxyType.GetMethod("EnsureDatabase"); - return (DbConnection)factoryMethod.Invoke(instance, new object[] { connectionString }); - } - - public static DbProviderFactory GetSqlCeProviderFactory() - { - var factoryMethod = proxyType.GetMethod("GetSqlCeProviderFactory"); - return (DbProviderFactory)factoryMethod.Invoke(instance, null); - } - } - -} diff --git a/NzbDrone.Core/ExternalNotification/ExternalNotificationDefinition.cs b/NzbDrone.Core/ExternalNotification/ExternalNotificationDefinition.cs index e1c9326fa..a0fac5405 100644 --- a/NzbDrone.Core/ExternalNotification/ExternalNotificationDefinition.cs +++ b/NzbDrone.Core/ExternalNotification/ExternalNotificationDefinition.cs @@ -1,6 +1,5 @@ using System.Linq; using NzbDrone.Core.Datastore; -using PetaPoco; namespace NzbDrone.Core.ExternalNotification { diff --git a/NzbDrone.Core/Indexers/Indexer.cs b/NzbDrone.Core/Indexers/Indexer.cs index 4f263da98..45f60d89b 100644 --- a/NzbDrone.Core/Indexers/Indexer.cs +++ b/NzbDrone.Core/Indexers/Indexer.cs @@ -1,6 +1,6 @@ using System; using NzbDrone.Core.Datastore; -using PetaPoco; + namespace NzbDrone.Core.Indexers { diff --git a/NzbDrone.Core/Indexers/IndexerService.cs b/NzbDrone.Core/Indexers/IndexerService.cs index 7200ce18d..3c0a1c352 100644 --- a/NzbDrone.Core/Indexers/IndexerService.cs +++ b/NzbDrone.Core/Indexers/IndexerService.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using NLog; using NzbDrone.Core.Lifecycle; -using PetaPoco; + namespace NzbDrone.Core.Indexers { diff --git a/NzbDrone.Core/Indexers/NewznabDefinition.cs b/NzbDrone.Core/Indexers/NewznabDefinition.cs index fc07515d9..bc8fe153c 100644 --- a/NzbDrone.Core/Indexers/NewznabDefinition.cs +++ b/NzbDrone.Core/Indexers/NewznabDefinition.cs @@ -1,7 +1,7 @@ using System; using System.ComponentModel.DataAnnotations; using NzbDrone.Core.Datastore; -using PetaPoco; + namespace NzbDrone.Core.Indexers { diff --git a/NzbDrone.Core/Indexers/NewznabService.cs b/NzbDrone.Core/Indexers/NewznabService.cs index 8c1cea854..39d406ed0 100644 --- a/NzbDrone.Core/Indexers/NewznabService.cs +++ b/NzbDrone.Core/Indexers/NewznabService.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Net; using NLog; using NzbDrone.Core.Lifecycle; -using PetaPoco; + namespace NzbDrone.Core.Indexers { diff --git a/NzbDrone.Core/Jobs/RefreshEpsiodeMetadata.cs b/NzbDrone.Core/Jobs/RefreshEpsiodeMetadata.cs index 335cf81a4..9ba842aa4 100644 --- a/NzbDrone.Core/Jobs/RefreshEpsiodeMetadata.cs +++ b/NzbDrone.Core/Jobs/RefreshEpsiodeMetadata.cs @@ -15,17 +15,15 @@ namespace NzbDrone.Core.Jobs { private readonly IMediaFileService _mediaFileService; private readonly ISeriesService _seriesService; - private readonly MetadataProvider _metadataProvider; private readonly ISeriesRepository _seriesRepository; private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); public RefreshEpisodeMetadata(IMediaFileService mediaFileService, ISeriesService seriesService, - MetadataProvider metadataProvider,ISeriesRepository seriesRepository) + ISeriesRepository seriesRepository) { _mediaFileService = mediaFileService; _seriesService = seriesService; - _metadataProvider = metadataProvider; _seriesRepository = seriesRepository; } @@ -68,16 +66,6 @@ namespace NzbDrone.Core.Jobs return; } - try - { - _metadataProvider.CreateForEpisodeFiles(episodeFiles.ToList()); - } - - catch (Exception e) - { - Logger.WarnException("An error has occurred while refreshing episode metadata", e); - } - notification.CurrentMessage = String.Format("Epsiode metadata refresh completed for {0}", series.Title); } } diff --git a/NzbDrone.Core/Jobs/RenameSeasonJob.cs b/NzbDrone.Core/Jobs/RenameSeasonJob.cs index 518a03935..da01a1d2f 100644 --- a/NzbDrone.Core/Jobs/RenameSeasonJob.cs +++ b/NzbDrone.Core/Jobs/RenameSeasonJob.cs @@ -16,20 +16,16 @@ namespace NzbDrone.Core.Jobs { private readonly IMediaFileService _mediaFileService; private readonly DiskScanProvider _diskScanProvider; - private readonly ISeriesService _seriesService; - private readonly MetadataProvider _metadataProvider; private readonly ISeriesRepository _seriesRepository; private readonly IEventAggregator _eventAggregator; private static readonly Logger logger = LogManager.GetCurrentClassLogger(); public RenameSeasonJob(IMediaFileService mediaFileService, DiskScanProvider diskScanProvider, ISeriesService seriesService, - MetadataProvider metadataProvider, ISeriesRepository seriesRepository, IEventAggregator eventAggregator) + ISeriesRepository seriesRepository, IEventAggregator eventAggregator) { _mediaFileService = mediaFileService; _diskScanProvider = diskScanProvider; - _seriesService = seriesService; - _metadataProvider = metadataProvider; _seriesRepository = seriesRepository; _eventAggregator = eventAggregator; } @@ -96,14 +92,7 @@ namespace NzbDrone.Core.Jobs return; } - //Remove & Create Metadata for episode files - //Todo: Add a metadata manager to avoid this hack - _metadataProvider.RemoveForEpisodeFiles(oldEpisodeFiles); - _metadataProvider.CreateForEpisodeFiles(newEpisodeFiles); - //Start AfterRename - var message = String.Format("Renamed: Series {0}, Season: {1}", series.Title, options.SeasonNumber); - _eventAggregator.Publish(new SeriesRenamedEvent(series)); notification.CurrentMessage = String.Format("Rename completed for {0} Season {1}", series.Title, options.SeasonNumber); diff --git a/NzbDrone.Core/Jobs/RenameSeriesJob.cs b/NzbDrone.Core/Jobs/RenameSeriesJob.cs index 94979a0dc..fa11bf111 100644 --- a/NzbDrone.Core/Jobs/RenameSeriesJob.cs +++ b/NzbDrone.Core/Jobs/RenameSeriesJob.cs @@ -15,18 +15,16 @@ namespace NzbDrone.Core.Jobs { private readonly IMediaFileService _mediaFileService; private readonly DiskScanProvider _diskScanProvider; - private readonly MetadataProvider _metadataProvider; private readonly ISeriesRepository _seriesRepository; private readonly IEventAggregator _eventAggregator; private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); public RenameSeriesJob(IMediaFileService mediaFileService, DiskScanProvider diskScanProvider, - MetadataProvider metadataProvider,ISeriesRepository seriesRepository,IEventAggregator eventAggregator) + ISeriesRepository seriesRepository,IEventAggregator eventAggregator) { _mediaFileService = mediaFileService; _diskScanProvider = diskScanProvider; - _metadataProvider = metadataProvider; _seriesRepository = seriesRepository; _eventAggregator = eventAggregator; } @@ -91,10 +89,6 @@ namespace NzbDrone.Core.Jobs } } - //Remove & Create Metadata for episode files - _metadataProvider.RemoveForEpisodeFiles(oldEpisodeFiles); - _metadataProvider.CreateForEpisodeFiles(newEpisodeFiles); - //Start AfterRename _eventAggregator.Publish(new SeriesRenamedEvent(series)); diff --git a/NzbDrone.Core/Jobs/UpdateInfoJob.cs b/NzbDrone.Core/Jobs/UpdateInfoJob.cs index d15a60f84..6a37c7231 100644 --- a/NzbDrone.Core/Jobs/UpdateInfoJob.cs +++ b/NzbDrone.Core/Jobs/UpdateInfoJob.cs @@ -4,6 +4,7 @@ using System.Linq; using NLog; using NzbDrone.Core.Configuration; using NzbDrone.Core.Datastore; +using NzbDrone.Core.ReferenceData; using NzbDrone.Core.Tv; using NzbDrone.Core.Helpers; using NzbDrone.Core.Model.Notification; @@ -17,17 +18,17 @@ namespace NzbDrone.Core.Jobs { private readonly ISeriesService _seriesService; private readonly IEpisodeService _episodeService; - private readonly ReferenceDataProvider _referenceDataProvider; + private readonly DailySeriesService _dailySeriesService; private readonly IConfigService _configService; private readonly ISeriesRepository _seriesRepository; private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); public UpdateInfoJob(ISeriesService seriesService, IEpisodeService episodeService, - ReferenceDataProvider referenceDataProvider, IConfigService configService, ISeriesRepository seriesRepository) + DailySeriesService dailySeriesService, IConfigService configService, ISeriesRepository seriesRepository) { _seriesService = seriesService; _episodeService = episodeService; - _referenceDataProvider = referenceDataProvider; + _dailySeriesService = dailySeriesService; _configService = configService; _seriesRepository = seriesRepository; } @@ -67,7 +68,7 @@ namespace NzbDrone.Core.Jobs } //Update any Daily Series in the DB with the IsDaily flag - _referenceDataProvider.UpdateDailySeries(); + _dailySeriesService.UpdateDailySeries(); foreach (var seriesToUpdate in ListOfSeriesToUpdate) { diff --git a/NzbDrone.Core/Jobs/UpdateSceneMappingsJob.cs b/NzbDrone.Core/Jobs/UpdateSceneMappingsJob.cs index 7812d2eb4..ada62d5f6 100644 --- a/NzbDrone.Core/Jobs/UpdateSceneMappingsJob.cs +++ b/NzbDrone.Core/Jobs/UpdateSceneMappingsJob.cs @@ -2,16 +2,17 @@ using System.Linq; using NzbDrone.Core.Model.Notification; using NzbDrone.Core.Providers; +using NzbDrone.Core.ReferenceData; namespace NzbDrone.Core.Jobs { public class UpdateSceneMappingsJob : IJob { - private readonly SceneMappingProvider _sceneNameMappingProvider; + private readonly SceneMappingService _sceneNameMappingService; - public UpdateSceneMappingsJob(SceneMappingProvider sceneNameMappingProvider) + public UpdateSceneMappingsJob(SceneMappingService sceneNameMappingService) { - _sceneNameMappingProvider = sceneNameMappingProvider; + _sceneNameMappingService = sceneNameMappingService; } public UpdateSceneMappingsJob() @@ -31,7 +32,7 @@ namespace NzbDrone.Core.Jobs public virtual void Start(ProgressNotification notification, dynamic options) { - _sceneNameMappingProvider.UpdateMappings(); + _sceneNameMappingService.UpdateMappings(); } } } \ No newline at end of file diff --git a/NzbDrone.Core/NzbDrone.Core.csproj b/NzbDrone.Core/NzbDrone.Core.csproj index 9a9bfa2d5..7f38f6547 100644 --- a/NzbDrone.Core/NzbDrone.Core.csproj +++ b/NzbDrone.Core/NzbDrone.Core.csproj @@ -151,18 +151,6 @@ True ..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll - - False - ..\Libraries\Migrator.NET\Migrator.dll - - - False - ..\Libraries\Migrator.NET\Migrator.Framework.dll - - - False - ..\Libraries\Migrator.NET\Migrator.Providers.dll - False ..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll @@ -221,45 +209,8 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -310,6 +261,9 @@ + + + @@ -356,7 +310,6 @@ - @@ -392,7 +345,6 @@ - @@ -534,14 +486,14 @@ Code - + Code Code - + Code @@ -593,7 +545,7 @@ - + diff --git a/NzbDrone.Core/Providers/BackupProvider.cs b/NzbDrone.Core/Providers/BackupProvider.cs index 303ac9142..98aac9ad3 100644 --- a/NzbDrone.Core/Providers/BackupProvider.cs +++ b/NzbDrone.Core/Providers/BackupProvider.cs @@ -23,13 +23,11 @@ namespace NzbDrone.Core.Providers public virtual string CreateBackupZip() { - var dbFile = _environmentProvider.GetSqlCeMainDbPath(); var configFile = _environmentProvider.GetConfigPath(); var zipFile = _environmentProvider.GetConfigBackupFile(); using (var zip = new ZipFile()) { - zip.AddFile(dbFile, String.Empty); zip.AddFile(configFile, String.Empty); zip.Save(zipFile); } diff --git a/NzbDrone.Core/Providers/MetadataProvider.cs b/NzbDrone.Core/Providers/MetadataProvider.cs deleted file mode 100644 index 8b9e115a0..000000000 --- a/NzbDrone.Core/Providers/MetadataProvider.cs +++ /dev/null @@ -1,172 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using NLog; -using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Tv; -using NzbDrone.Core.Providers.Metadata; -using NzbDrone.Core.Repository; -using PetaPoco; -using TvdbLib.Data; - -namespace NzbDrone.Core.Providers -{ - public class MetadataProvider - { - private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - private readonly IDatabase _database; - - private IList _metadataProviders; - private readonly TvDbProvider _tvDbProvider; - - public MetadataProvider(IDatabase database, IEnumerable metadataProviders, - TvDbProvider tvDbProvider) - { - _database = database; - _metadataProviders = metadataProviders.ToList(); - _tvDbProvider = tvDbProvider; - - Initialize(_metadataProviders); - } - - public MetadataProvider() - { - - } - - public virtual List All() - { - return _database.Fetch(); - } - - public virtual void SaveSettings(MetadataDefinition settings) - { - if (settings.Id == 0) - { - Logger.Debug("Adding Metabase definition for {0}", settings.Name); - _database.Insert(settings); - } - - else - { - Logger.Debug("Updating Metabase definition for {0}", settings.Name); - _database.Update(settings); - } - } - - public virtual MetadataDefinition GetSettings(Type type) - { - return _database.SingleOrDefault("WHERE MetadataProviderType = @0", type.ToString()); - } - - public virtual IList GetEnabledMetabaseProviders() - { - var all = All(); - return _metadataProviders.Where(i => all.Exists(c => c.MetadataProviderType == i.GetType().ToString() && c.Enable)).ToList(); - } - - private void Initialize(IList metabaseProviders) - { - Logger.Debug("Initializing metabases. Count {0}", metabaseProviders.Count); - - _metadataProviders = metabaseProviders; - - var currentNotifiers = All(); - - foreach (var notificationProvider in metabaseProviders) - { - MetadataBase metadataProviderLocal = notificationProvider; - if (!currentNotifiers.Exists(c => c.MetadataProviderType == metadataProviderLocal.GetType().ToString())) - { - var settings = new MetadataDefinition - { - Enable = false, - MetadataProviderType = metadataProviderLocal.GetType().ToString(), - Name = metadataProviderLocal.Name - }; - - SaveSettings(settings); - } - } - } - - public virtual void CreateForSeries(Series series) - { - var tvDbSeries = _tvDbProvider.GetSeries(series.TvDbId, false, true); - - CreateForSeries(series, tvDbSeries); - } - - public virtual void CreateForSeries(Series series, TvdbSeries tvDbSeries) - { - foreach (var provider in _metadataProviders.Where(i => GetSettings(i.GetType()).Enable)) - { - provider.CreateForSeries(series, tvDbSeries); - } - } - - public virtual void CreateForEpisodeFile(EpisodeFile episodeFile) - { - var tvDbSeries = _tvDbProvider.GetSeries(episodeFile.SeriesId, true, true); - - CreateForEpisodeFile(episodeFile, tvDbSeries); - } - - public virtual void CreateForEpisodeFile(EpisodeFile episodeFile, TvdbSeries tvDbSeries) - { - foreach (var provider in _metadataProviders.Where(i => GetSettings(i.GetType()).Enable)) - { - provider.CreateForEpisodeFile(episodeFile, tvDbSeries); - } - } - - public virtual void CreateForEpisodeFiles(List episodeFiles) - { - if (episodeFiles == null || !episodeFiles.Any()) - { - Logger.Warn("No episode files, no metadata will be created."); - throw new ArgumentException("EpsiodeFiles must not be null or empty", "episodeFiles"); - } - - Logger.Trace("Creating metadata for {0} files.", episodeFiles.Count); - - var tvDbSeries = _tvDbProvider.GetSeries(episodeFiles.First().SeriesId, true, true); - - foreach(var episodeFile in episodeFiles) - { - foreach (var provider in _metadataProviders.Where(i => GetSettings(i.GetType()).Enable)) - { - Logger.Trace("Creating {0} metadata for {1}", provider.Name, episodeFile.Id); - provider.CreateForEpisodeFile(episodeFile, tvDbSeries); - } - } - } - - public virtual void RemoveForSeries(Series series) - { - foreach (var provider in _metadataProviders.Where(i => GetSettings(i.GetType()).Enable)) - { - provider.RemoveForSeries(series); - } - } - - public virtual void RemoveForEpisodeFile(EpisodeFile episodeFile) - { - foreach (var provider in _metadataProviders.Where(i => GetSettings(i.GetType()).Enable)) - { - provider.RemoveForEpisodeFile(episodeFile); - } - } - - public virtual void RemoveForEpisodeFiles(List episodeFiles) - { - foreach (var episodeFile in episodeFiles) - { - foreach (var provider in _metadataProviders.Where(i => GetSettings(i.GetType()).Enable)) - { - provider.RemoveForEpisodeFile(episodeFile); - } - } - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Providers/PostDownloadProvider.cs b/NzbDrone.Core/Providers/PostDownloadProvider.cs index 24adcbbc4..fc2f32cfd 100644 --- a/NzbDrone.Core/Providers/PostDownloadProvider.cs +++ b/NzbDrone.Core/Providers/PostDownloadProvider.cs @@ -16,17 +16,13 @@ namespace NzbDrone.Core.Providers private static readonly Regex StatusRegex = new Regex(@"^_[\w_]*_", RegexOptions.Compiled); private readonly DiskProvider _diskProvider; private readonly DiskScanProvider _diskScanProvider; - private readonly ISeriesService _seriesService; - private readonly MetadataProvider _metadataProvider; private readonly ISeriesRepository _seriesRepository; public PostDownloadProvider(DiskProvider diskProvider, DiskScanProvider diskScanProvider, - ISeriesService seriesService, MetadataProvider metadataProvider,ISeriesRepository seriesRepository) + ISeriesService seriesService, ISeriesRepository seriesRepository) { _diskProvider = diskProvider; _diskScanProvider = diskScanProvider; - _seriesService = seriesService; - _metadataProvider = metadataProvider; _seriesRepository = seriesRepository; } @@ -108,10 +104,6 @@ namespace NzbDrone.Core.Providers var importedFiles = _diskScanProvider.Scan(series, subfolderInfo.FullName); importedFiles.ForEach(file => _diskScanProvider.MoveEpisodeFile(file, true)); - //Create Metadata for all the episode files found - if (importedFiles.Any()) - _metadataProvider.CreateForEpisodeFiles(importedFiles); - //Delete the folder only if folder is small enough if (_diskProvider.GetDirectorySize(subfolderInfo.FullName) < Constants.IgnoreFileSize) { @@ -176,7 +168,6 @@ namespace NzbDrone.Core.Providers if (episodeFile != null) { _diskScanProvider.MoveEpisodeFile(episodeFile, true); - _metadataProvider.CreateForEpisodeFile(episodeFile); } } diff --git a/NzbDrone.Core/Providers/ReferenceDataProvider.cs b/NzbDrone.Core/Providers/ReferenceDataProvider.cs deleted file mode 100644 index 716f0874f..000000000 --- a/NzbDrone.Core/Providers/ReferenceDataProvider.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using NLog; -using Newtonsoft.Json; -using NzbDrone.Common; -using NzbDrone.Core.Configuration; -using NzbDrone.Core.Providers.Core; -using NzbDrone.Core.Repository; -using PetaPoco; - -namespace NzbDrone.Core.Providers -{ - public class ReferenceDataProvider - { - private readonly IDatabase _database; - private readonly HttpProvider _httpProvider; - private readonly IConfigService _configService; - - private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - - public ReferenceDataProvider(IDatabase database, HttpProvider httpProvider, IConfigService configService) - { - _database = database; - _httpProvider = httpProvider; - _configService = configService; - } - - public virtual void UpdateDailySeries() - { - //Update all series in DB - //DailySeries.csv - - var seriesIds = GetDailySeriesIds(); - - if (seriesIds.Any()) - { - var dailySeriesString = String.Join(", ", seriesIds); - var sql = String.Format("UPDATE Series SET IsDaily = 1 WHERE SeriesId in ({0})", dailySeriesString); - - _database.Execute(sql); - } - } - - public virtual bool IsSeriesDaily(int seriesId) - { - return GetDailySeriesIds().Contains(seriesId); - } - - public List GetDailySeriesIds() - { - try - { - var dailySeriesIds = _httpProvider.DownloadString(_configService.ServiceRootUrl + "/DailySeries/AllIds"); - - var seriesIds = JsonConvert.DeserializeObject>(dailySeriesIds); - - return seriesIds; - } - catch (Exception ex) - { - Logger.WarnException("Failed to get Daily Series", ex); - return new List(); - } - - } - } -} diff --git a/NzbDrone.Core/Providers/SceneMappingProvider.cs b/NzbDrone.Core/Providers/SceneMappingProvider.cs deleted file mode 100644 index 4c99ca879..000000000 --- a/NzbDrone.Core/Providers/SceneMappingProvider.cs +++ /dev/null @@ -1,114 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using NLog; -using Newtonsoft.Json; -using NzbDrone.Common; -using NzbDrone.Core.Configuration; -using NzbDrone.Core.Providers.Core; -using NzbDrone.Core.Repository; -using PetaPoco; - -namespace NzbDrone.Core.Providers -{ - public class SceneMappingProvider - { - private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - private readonly IDatabase _database; - private readonly HttpProvider _httpProvider; - private readonly IConfigService _configService; - - public SceneMappingProvider(IDatabase database, HttpProvider httpProvider, IConfigService configService) - { - _database = database; - _httpProvider = httpProvider; - _configService = configService; - } - - public SceneMappingProvider() - { - - } - - public virtual bool UpdateMappings() - { - try - { - var mappingsJson = _httpProvider.DownloadString(_configService.ServiceRootUrl + "/SceneMapping/Active"); - var mappings = JsonConvert.DeserializeObject>(mappingsJson); - - Logger.Debug("Deleting all existing Scene Mappings."); - _database.Delete(String.Empty); - - Logger.Debug("Adding Scene Mappings"); - _database.InsertMany(mappings); - } - - catch (Exception ex) - { - Logger.InfoException("Failed to Update Scene Mappings:", ex); - return false; - } - return true; - } - - public virtual string GetSceneName(int seriesId, int seasonNumber = -1) - { - UpdateIfEmpty(); - - var item = _database.FirstOrDefault("WHERE SeriesId = @0 AND SeasonNumber = @1", seriesId, seasonNumber); - - if (item == null) - return null; - - return item.SceneName; - } - - public virtual Nullable GetSeriesId(string cleanName) - { - UpdateIfEmpty(); - - var item = _database.SingleOrDefault("WHERE CleanTitle = @0", cleanName); - - if (item == null) - return null; - - return item.SeriesId; - } - - public void UpdateIfEmpty() - { - var count = _database.ExecuteScalar("SELECT COUNT(*) FROM SceneMappings"); - - if (count == 0) - UpdateMappings(); - } - - public virtual bool SubmitMapping(int id, string postTitle) - { - Logger.Trace("Parsing example post"); - var episodeParseResult = Parser.ParseTitle(postTitle); - var cleanTitle = episodeParseResult.CleanTitle; - var title = episodeParseResult.SeriesTitle.Replace('.', ' '); - Logger.Trace("Example post parsed. CleanTitle: {0}, Title: {1}", cleanTitle, title); - - var newMapping = String.Format("/SceneMapping/AddPending?cleanTitle={0}&id={1}&title={2}", cleanTitle, id, title); - var response = _httpProvider.DownloadString(_configService.ServiceRootUrl + newMapping); - - if (JsonConvert.DeserializeObject(response).Equals("Ok")) - return true; - - return false; - } - - public virtual string GetCleanName(int seriesId) - { - var item = _database.FirstOrDefault("WHERE SeriesId = @0", seriesId); - - if (item == null) - return null; - - return item.CleanTitle; - } - } -} diff --git a/NzbDrone.Core/Providers/Search/DailyEpisodeSearch.cs b/NzbDrone.Core/Providers/Search/DailyEpisodeSearch.cs index 0ce9da971..acc76bc71 100644 --- a/NzbDrone.Core/Providers/Search/DailyEpisodeSearch.cs +++ b/NzbDrone.Core/Providers/Search/DailyEpisodeSearch.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using NLog; using NzbDrone.Core.Download; using NzbDrone.Core.Indexers; +using NzbDrone.Core.ReferenceData; using NzbDrone.Core.Tv; using NzbDrone.Core.Model; using NzbDrone.Core.Model.Notification; @@ -21,9 +22,9 @@ namespace NzbDrone.Core.Providers.Search private static readonly Logger logger = LogManager.GetCurrentClassLogger(); public DailyEpisodeSearch(ISeriesService seriesService, IEpisodeService episodeService, DownloadProvider downloadProvider, IIndexerService indexerService, - SceneMappingProvider sceneMappingProvider, AllowedDownloadSpecification allowedDownloadSpecification, + SceneMappingService sceneMappingService, AllowedDownloadSpecification allowedDownloadSpecification, ISeriesRepository seriesRepository) - : base(seriesService, seriesRepository, episodeService, downloadProvider, indexerService, sceneMappingProvider, + : base(seriesService, seriesRepository, episodeService, downloadProvider, indexerService, sceneMappingService, allowedDownloadSpecification) { _seriesRepository = seriesRepository; diff --git a/NzbDrone.Core/Providers/Search/EpisodeSearch.cs b/NzbDrone.Core/Providers/Search/EpisodeSearch.cs index 217735d5a..dc2009229 100644 --- a/NzbDrone.Core/Providers/Search/EpisodeSearch.cs +++ b/NzbDrone.Core/Providers/Search/EpisodeSearch.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using NLog; using NzbDrone.Core.Download; using NzbDrone.Core.Indexers; +using NzbDrone.Core.ReferenceData; using NzbDrone.Core.Tv; using NzbDrone.Core.Model; using NzbDrone.Core.Model.Notification; @@ -20,9 +21,9 @@ namespace NzbDrone.Core.Providers.Search private static readonly Logger logger = LogManager.GetCurrentClassLogger(); public EpisodeSearch(ISeriesService seriesService, IEpisodeService episodeService, DownloadProvider downloadProvider, IIndexerService indexerService, - SceneMappingProvider sceneMappingProvider, AllowedDownloadSpecification allowedDownloadSpecification, + SceneMappingService sceneMappingService, AllowedDownloadSpecification allowedDownloadSpecification, ISeriesRepository seriesRepository) - : base(seriesService,seriesRepository, episodeService, downloadProvider, indexerService, sceneMappingProvider, + : base(seriesService,seriesRepository, episodeService, downloadProvider, indexerService, sceneMappingService, allowedDownloadSpecification) { } diff --git a/NzbDrone.Core/Providers/Search/PartialSeasonSearch.cs b/NzbDrone.Core/Providers/Search/PartialSeasonSearch.cs index a03cc7821..894689609 100644 --- a/NzbDrone.Core/Providers/Search/PartialSeasonSearch.cs +++ b/NzbDrone.Core/Providers/Search/PartialSeasonSearch.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using NLog; using NzbDrone.Core.Download; using NzbDrone.Core.Indexers; +using NzbDrone.Core.ReferenceData; using NzbDrone.Core.Tv; using NzbDrone.Core.Model; using NzbDrone.Core.Model.Notification; @@ -20,9 +21,9 @@ namespace NzbDrone.Core.Providers.Search private static readonly Logger logger = LogManager.GetCurrentClassLogger(); public PartialSeasonSearch(ISeriesService seriesService, IEpisodeService episodeService, DownloadProvider downloadProvider, IIndexerService indexerService, - SceneMappingProvider sceneMappingProvider, AllowedDownloadSpecification allowedDownloadSpecification, + SceneMappingService sceneMappingService, AllowedDownloadSpecification allowedDownloadSpecification, ISeriesRepository seriesRepository) - : base(seriesService, seriesRepository, episodeService, downloadProvider, indexerService, sceneMappingProvider, + : base(seriesService, seriesRepository, episodeService, downloadProvider, indexerService, sceneMappingService, allowedDownloadSpecification) { } diff --git a/NzbDrone.Core/Providers/Search/SearchBase.cs b/NzbDrone.Core/Providers/Search/SearchBase.cs index bb1c5b6e1..202e5094d 100644 --- a/NzbDrone.Core/Providers/Search/SearchBase.cs +++ b/NzbDrone.Core/Providers/Search/SearchBase.cs @@ -6,6 +6,7 @@ using NLog; using NzbDrone.Core.Datastore; using NzbDrone.Core.Download; using NzbDrone.Core.Indexers; +using NzbDrone.Core.ReferenceData; using NzbDrone.Core.Tv; using NzbDrone.Core.Model; using NzbDrone.Core.Model.Notification; @@ -21,13 +22,13 @@ namespace NzbDrone.Core.Providers.Search protected readonly IEpisodeService _episodeService; protected readonly DownloadProvider _downloadProvider; protected readonly IIndexerService _indexerService; - protected readonly SceneMappingProvider _sceneMappingProvider; + protected readonly SceneMappingService _sceneMappingService; protected readonly AllowedDownloadSpecification _allowedDownloadSpecification; private static readonly Logger logger = LogManager.GetCurrentClassLogger(); protected SearchBase(ISeriesService seriesService,ISeriesRepository seriesRepository, IEpisodeService episodeService, DownloadProvider downloadProvider, - IIndexerService indexerService, SceneMappingProvider sceneMappingProvider, + IIndexerService indexerService, SceneMappingService sceneMappingService, AllowedDownloadSpecification allowedDownloadSpecification) { _seriesService = seriesService; @@ -35,7 +36,7 @@ namespace NzbDrone.Core.Providers.Search _episodeService = episodeService; _downloadProvider = downloadProvider; _indexerService = indexerService; - _sceneMappingProvider = sceneMappingProvider; + _sceneMappingService = sceneMappingService; _allowedDownloadSpecification = allowedDownloadSpecification; } @@ -168,12 +169,12 @@ namespace NzbDrone.Core.Providers.Search public virtual string GetSearchTitle(Series series, int seasonNumber = -1) { - var seasonTitle = _sceneMappingProvider.GetSceneName(series.Id, seasonNumber); + var seasonTitle = _sceneMappingService.GetSceneName(series.Id, seasonNumber); if(!String.IsNullOrWhiteSpace(seasonTitle)) return seasonTitle; - var title = _sceneMappingProvider.GetSceneName(series.Id); + var title = _sceneMappingService.GetSceneName(series.Id); if (String.IsNullOrWhiteSpace(title)) { diff --git a/NzbDrone.Core/Providers/TvRageMappingProvider.cs b/NzbDrone.Core/Providers/TvRageMappingProvider.cs index 19cea428f..4498191d2 100644 --- a/NzbDrone.Core/Providers/TvRageMappingProvider.cs +++ b/NzbDrone.Core/Providers/TvRageMappingProvider.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Text; using NLog; using NzbDrone.Core.Datastore; +using NzbDrone.Core.ReferenceData; using NzbDrone.Core.Tv; using NzbDrone.Core.Model.TvRage; using NzbDrone.Core.Repository; @@ -12,16 +13,16 @@ namespace NzbDrone.Core.Providers { public class TvRageMappingProvider { - private readonly SceneMappingProvider _sceneMappingProvider; + private readonly SceneMappingService _sceneMappingService; private readonly TvRageProvider _tvRageProvider; private readonly IEpisodeService _episodeService; private static readonly Logger logger = LogManager.GetCurrentClassLogger(); - public TvRageMappingProvider(SceneMappingProvider sceneMappingProvider, + public TvRageMappingProvider(SceneMappingService sceneMappingService, TvRageProvider tvRageProvider, IEpisodeService episodeService) { - _sceneMappingProvider = sceneMappingProvider; + _sceneMappingService = sceneMappingService; _tvRageProvider = tvRageProvider; _episodeService = episodeService; } @@ -34,7 +35,7 @@ namespace NzbDrone.Core.Providers { var firstEpisode = _episodeService.GetEpisode(series.Id, 1, 1); - var cleanName = _sceneMappingProvider.GetCleanName(series.Id); + var cleanName = _sceneMappingService.GetCleanName(series.Id); var results = _tvRageProvider.SearchSeries(series.Title); var result = ProcessResults(results, series, cleanName, firstEpisode); diff --git a/NzbDrone.Core/Qualities/QualityProfileService.cs b/NzbDrone.Core/Qualities/QualityProfileService.cs index f5173d8c8..b7b429db0 100644 --- a/NzbDrone.Core/Qualities/QualityProfileService.cs +++ b/NzbDrone.Core/Qualities/QualityProfileService.cs @@ -4,7 +4,7 @@ using System.Linq; using NLog; using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Qualities; -using PetaPoco; + namespace NzbDrone.Core.Qualities { diff --git a/NzbDrone.Core/Qualities/QualitySize.cs b/NzbDrone.Core/Qualities/QualitySize.cs index 0cc0ee2f9..3e9e31032 100644 --- a/NzbDrone.Core/Qualities/QualitySize.cs +++ b/NzbDrone.Core/Qualities/QualitySize.cs @@ -1,6 +1,6 @@ using System.Linq; using NzbDrone.Core.Datastore; -using PetaPoco; + namespace NzbDrone.Core.Qualities { diff --git a/NzbDrone.Core/ReferenceData/DailySeriesDataProxy.cs b/NzbDrone.Core/ReferenceData/DailySeriesDataProxy.cs new file mode 100644 index 000000000..10dc9888f --- /dev/null +++ b/NzbDrone.Core/ReferenceData/DailySeriesDataProxy.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NLog; +using Newtonsoft.Json; +using NzbDrone.Common; +using NzbDrone.Core.Configuration; + +namespace NzbDrone.Core.ReferenceData +{ + + public interface IDailySeriesDataProxy + { + IEnumerable GetDailySeriesIds(); + } + + public class DailySeriesDataProxy : IDailySeriesDataProxy + { + private readonly HttpProvider _httpProvider; + private readonly IConfigService _configService; + private readonly Logger _logger; + + public DailySeriesDataProxy(HttpProvider httpProvider, IConfigService configService, Logger logger) + { + _httpProvider = httpProvider; + _configService = configService; + _logger = logger; + } + + public IEnumerable GetDailySeriesIds() + { + try + { + var dailySeriesIds = _httpProvider.DownloadString(_configService.ServiceRootUrl + "/DailySeries/AllIds"); + + var seriesIds = JsonConvert.DeserializeObject>(dailySeriesIds); + + return seriesIds; + } + catch (Exception ex) + { + _logger.WarnException("Failed to get Daily Series", ex); + return new List(); + } + + } + } +} \ No newline at end of file diff --git a/NzbDrone.Core/ReferenceData/DailySeriesService.cs b/NzbDrone.Core/ReferenceData/DailySeriesService.cs index 6ae76cec6..3d7ceceea 100644 --- a/NzbDrone.Core/ReferenceData/DailySeriesService.cs +++ b/NzbDrone.Core/ReferenceData/DailySeriesService.cs @@ -1,66 +1,32 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using NLog; -using Newtonsoft.Json; -using NzbDrone.Common; -using NzbDrone.Core.Providers.Core; -using PetaPoco; +using System.Linq; +using NzbDrone.Core.Tv; namespace NzbDrone.Core.ReferenceData { public class DailySeriesService { - private readonly IDatabase _database; - private readonly HttpProvider _httpProvider; - private readonly ConfigProvider _configProvider; + private readonly IDailySeriesDataProxy _proxy; + private readonly ISeriesService _seriesService; - private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - - public DailySeriesService(IDatabase database, HttpProvider httpProvider, ConfigProvider configProvider) + public DailySeriesService(IDailySeriesDataProxy proxy, ISeriesService seriesService) { - _database = database; - _httpProvider = httpProvider; - _configProvider = configProvider; + _proxy = proxy; + _seriesService = seriesService; } public virtual void UpdateDailySeries() { - //Update all series in DB - //DailySeries.csv - - var seriesIds = GetDailySeriesIds(); + var dailySeries = _proxy.GetDailySeriesIds(); - if (seriesIds.Any()) + foreach (var tvdbId in dailySeries) { - var dailySeriesString = String.Join(", ", seriesIds); - var sql = String.Format("UPDATE Series SET IsDaily = 1 WHERE SeriesId in ({0})", dailySeriesString); + var series = _seriesService.FindByTvdbId(tvdbId); - _database.Execute(sql); + if (series != null) + { + _seriesService.SetSeriesType(series.Id, SeriesType.Daily); + } } } - - public virtual bool IsSeriesDaily(int seriesId) - { - return GetDailySeriesIds().Contains(seriesId); - } - - public List GetDailySeriesIds() - { - try - { - var dailySeriesIds = _httpProvider.DownloadString(_configProvider.ServiceRootUrl + "/DailySeries/AllIds"); - - var seriesIds = JsonConvert.DeserializeObject>(dailySeriesIds); - - return seriesIds; - } - catch (Exception ex) - { - Logger.WarnException("Failed to get Daily Series", ex); - return new List(); - } - - } } } diff --git a/NzbDrone.Core/ReferenceData/SceneMapping.cs b/NzbDrone.Core/ReferenceData/SceneMapping.cs new file mode 100644 index 000000000..e92d9b260 --- /dev/null +++ b/NzbDrone.Core/ReferenceData/SceneMapping.cs @@ -0,0 +1,13 @@ +using System.Linq; +using NzbDrone.Core.Datastore; + +namespace NzbDrone.Core.ReferenceData +{ + public class SceneMapping : ModelBase + { + public string CleanTitle { get; set; } + public int TvdbId { get; set; } + public string SceneName { get; set; } + public int SeasonNumber { get; set; } + } +} \ No newline at end of file diff --git a/NzbDrone.Core/ReferenceData/SceneMappingProvider.cs b/NzbDrone.Core/ReferenceData/SceneMappingProvider.cs new file mode 100644 index 000000000..519a57a3a --- /dev/null +++ b/NzbDrone.Core/ReferenceData/SceneMappingProvider.cs @@ -0,0 +1,73 @@ +using System.Linq; +using System; +using NLog; +using NzbDrone.Core.Lifecycle; + +namespace NzbDrone.Core.ReferenceData +{ + public class SceneMappingService : IInitializable + { + private readonly ISceneMappingRepository _repository; + private readonly ISceneMappingProxy _sceneMappingProxy; + private readonly Logger _logger; + + public SceneMappingService(ISceneMappingRepository repository, ISceneMappingProxy sceneMappingProxy, Logger logger) + { + _repository = repository; + _sceneMappingProxy = sceneMappingProxy; + _logger = logger; + } + + public void UpdateMappings() + { + try + { + var mappings = _sceneMappingProxy.Fetch(); + + _repository.Purge(); + _repository.InsertMany(mappings); + } + catch (Exception ex) + { + _logger.InfoException("Failed to Update Scene Mappings:", ex); + } + } + + public virtual string GetSceneName(int tvdbId, int seasonNumber = -1) + { + var mapping = _repository.FindByTvdbId(tvdbId); + + if(mapping == null) return null; + + return mapping.SceneName; + } + + public virtual Nullable GetTvDbId(string cleanName) + { + var mapping = _repository.FindByCleanTitle(cleanName); + + if (mapping == null) + return null; + + return mapping.TvdbId; + } + + + public virtual string GetCleanName(int tvdbId) + { + var mapping = _repository.FindByTvdbId(tvdbId); + + if (mapping == null) return null; + + return mapping.CleanTitle; + } + + public void Init() + { + if (!_repository.HasItems()) + { + UpdateMappings(); + } + } + } +} diff --git a/NzbDrone.Core/ReferenceData/SceneMappingProxy.cs b/NzbDrone.Core/ReferenceData/SceneMappingProxy.cs new file mode 100644 index 000000000..5f4eefaa4 --- /dev/null +++ b/NzbDrone.Core/ReferenceData/SceneMappingProxy.cs @@ -0,0 +1,49 @@ +using System.Collections.Generic; +using System.Linq; +using Newtonsoft.Json; +using NzbDrone.Common; +using NzbDrone.Core.Configuration; + +namespace NzbDrone.Core.ReferenceData +{ + public interface ISceneMappingProxy + { + List Fetch(); + } + + public class SceneMappingProxy : ISceneMappingProxy + { + private readonly HttpProvider _httpProvider; + private readonly IConfigService _configService; + + public SceneMappingProxy(HttpProvider httpProvider, IConfigService configService) + { + _httpProvider = httpProvider; + _configService = configService; + } + + public List Fetch() + { + var mappingsJson = _httpProvider.DownloadString(_configService.ServiceRootUrl + "/SceneMapping/Active"); + return JsonConvert.DeserializeObject>(mappingsJson); + } + + + /* public virtual bool SubmitMapping(int id, string postTitle) + { + Logger.Trace("Parsing example post"); + var episodeParseResult = Parser.ParseTitle(postTitle); + var cleanTitle = episodeParseResult.CleanTitle; + var title = episodeParseResult.SeriesTitle.Replace('.', ' '); + Logger.Trace("Example post parsed. CleanTitle: {0}, Title: {1}", cleanTitle, title); + + var newMapping = String.Format("/SceneMapping/AddPending?cleanTitle={0}&id={1}&title={2}", cleanTitle, id, title); + var response = _httpProvider.DownloadString(_configService.ServiceRootUrl + newMapping); + + if (JsonConvert.DeserializeObject(response).Equals("Ok")) + return true; + + return false; + }*/ + } +} \ No newline at end of file diff --git a/NzbDrone.Core/ReferenceData/SceneMappingRepository.cs b/NzbDrone.Core/ReferenceData/SceneMappingRepository.cs new file mode 100644 index 000000000..18984efbd --- /dev/null +++ b/NzbDrone.Core/ReferenceData/SceneMappingRepository.cs @@ -0,0 +1,30 @@ +using System.Linq; +using NzbDrone.Core.Datastore; + +namespace NzbDrone.Core.ReferenceData +{ + public interface ISceneMappingRepository : IBasicRepository + { + SceneMapping FindByTvdbId(int tvdbId); + SceneMapping FindByCleanTitle(string cleanTitle); + + } + + public class SceneMappingRepository : BasicRepository, ISceneMappingRepository + { + public SceneMappingRepository(IObjectDatabase objectDatabase) + : base(objectDatabase) + { + } + + public SceneMapping FindByTvdbId(int tvdbId) + { + return Queryable.SingleOrDefault(c => c.TvdbId == tvdbId); + } + + public SceneMapping FindByCleanTitle(string cleanTitle) + { + return Queryable.SingleOrDefault(c => c.CleanTitle == cleanTitle); + } + } +} \ No newline at end of file diff --git a/NzbDrone.Core/Repository/MetadataDefinition.cs b/NzbDrone.Core/Repository/MetadataDefinition.cs deleted file mode 100644 index 9147d4f02..000000000 --- a/NzbDrone.Core/Repository/MetadataDefinition.cs +++ /dev/null @@ -1,17 +0,0 @@ -using PetaPoco; - -namespace NzbDrone.Core.Repository -{ - [TableName("MetadataDefinitions")] - [PrimaryKey("Id", autoIncrement = true)] - public class MetadataDefinition - { - public int Id { get; set; } - - public bool Enable { get; set; } - - public string MetadataProviderType { get; set; } - - public string Name { get; set; } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Repository/SceneMapping.cs b/NzbDrone.Core/Repository/SceneMapping.cs deleted file mode 100644 index d32d0703d..000000000 --- a/NzbDrone.Core/Repository/SceneMapping.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Newtonsoft.Json; -using PetaPoco; - -namespace NzbDrone.Core.Repository -{ - [TableName("SceneMappings")] - [PrimaryKey("CleanTitle", autoIncrement = false)] - public class SceneMapping - { - public string CleanTitle { get; set; } - - [JsonProperty(PropertyName = "Id")] - public int SeriesId { get; set; } - - [JsonProperty(PropertyName = "Title")] - public string SceneName { get; set; } - - [JsonProperty(PropertyName = "Season")] - public int SeasonNumber { get; set; } - } -} \ No newline at end of file diff --git a/NzbDrone.Core/Repository/Search/SearchHistory.cs b/NzbDrone.Core/Repository/Search/SearchHistory.cs index b5289856a..6f922b717 100644 --- a/NzbDrone.Core/Repository/Search/SearchHistory.cs +++ b/NzbDrone.Core/Repository/Search/SearchHistory.cs @@ -2,12 +2,10 @@ using System.Collections.Generic; using System.ComponentModel; using NzbDrone.Core.Model; -using PetaPoco; + namespace NzbDrone.Core.Repository.Search { - [PrimaryKey("Id", autoIncrement = true)] - [TableName("SearchHistory")] public class SearchHistory { public int Id { get; set; } @@ -17,31 +15,22 @@ namespace NzbDrone.Core.Repository.Search public DateTime SearchTime { get; set; } public bool SuccessfulDownload { get; set; } - [ResultColumn] public List SearchHistoryItems { get; set; } - [Ignore] public List Successes { get; set; } - [ResultColumn] public string SeriesTitle { get; set; } - [ResultColumn] public bool IsDaily { get; set; } - [ResultColumn] public int? EpisodeNumber { get; set; } - [ResultColumn] public string EpisodeTitle { get; set; } - [ResultColumn] public DateTime AirDate { get; set; } - [ResultColumn] public int TotalItems { get; set; } - [ResultColumn] public int SuccessfulCount { get; set; } } } \ No newline at end of file diff --git a/NzbDrone.Core/Repository/Search/SearchHistoryItem.cs b/NzbDrone.Core/Repository/Search/SearchHistoryItem.cs index ae29d3430..e179f7c52 100644 --- a/NzbDrone.Core/Repository/Search/SearchHistoryItem.cs +++ b/NzbDrone.Core/Repository/Search/SearchHistoryItem.cs @@ -1,14 +1,10 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; using NzbDrone.Core.Model; using NzbDrone.Core.Qualities; -using PetaPoco; + namespace NzbDrone.Core.Repository.Search { - [PrimaryKey("Id", autoIncrement = true)] - [TableName("SearchHistoryItems")] public class SearchHistoryItem { public int Id { get; set; } diff --git a/NzbDrone.Core/Tv/SeasonRepository.cs b/NzbDrone.Core/Tv/SeasonRepository.cs index 67dc96d69..9323700b3 100644 --- a/NzbDrone.Core/Tv/SeasonRepository.cs +++ b/NzbDrone.Core/Tv/SeasonRepository.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Linq; using NLog; using NzbDrone.Core.Datastore; -using PetaPoco; + namespace NzbDrone.Core.Tv { diff --git a/NzbDrone.Core/Tv/Series.cs b/NzbDrone.Core/Tv/Series.cs index 38d3b06d4..aae84bee6 100644 --- a/NzbDrone.Core/Tv/Series.cs +++ b/NzbDrone.Core/Tv/Series.cs @@ -4,7 +4,7 @@ using System; using NzbDrone.Core.Datastore; using NzbDrone.Core.Model; using NzbDrone.Core.Qualities; -using PetaPoco; + using Sqo.Attributes; namespace NzbDrone.Core.Tv diff --git a/NzbDrone.Core/Tv/SeriesRepository.cs b/NzbDrone.Core/Tv/SeriesRepository.cs index 3d3c09218..57e5a6fc7 100644 --- a/NzbDrone.Core/Tv/SeriesRepository.cs +++ b/NzbDrone.Core/Tv/SeriesRepository.cs @@ -10,6 +10,9 @@ namespace NzbDrone.Core.Tv bool SeriesPathExists(string path); List Search(string title); Series GetByTitle(string cleanTitle); + Series FindByTvdbId(int tvdbId); + void SetSeriesType(int seriesId, SeriesType seriesType); + } public class SeriesRepository : BasicRepository, ISeriesRepository @@ -33,5 +36,15 @@ namespace NzbDrone.Core.Tv { return Queryable.SingleOrDefault(s => s.CleanTitle.Equals(cleanTitle)); } + + public Series FindByTvdbId(int tvdbId) + { + return Queryable.SingleOrDefault(s => s.TvDbId == tvdbId); + } + + public void SetSeriesType(int seriesId, SeriesType seriesType) + { + ObjectDatabase.UpdateField(new Series(){Id = seriesId, SeriesType =seriesType }, "SeriesType"); + } } } \ No newline at end of file diff --git a/NzbDrone.Core/Tv/SeriesService.cs b/NzbDrone.Core/Tv/SeriesService.cs index 41a495dff..3c6233743 100644 --- a/NzbDrone.Core/Tv/SeriesService.cs +++ b/NzbDrone.Core/Tv/SeriesService.cs @@ -10,6 +10,7 @@ using NzbDrone.Core.Datastore; using NzbDrone.Core.Model; using NzbDrone.Core.Providers; using NzbDrone.Core.Qualities; +using NzbDrone.Core.ReferenceData; using NzbDrone.Core.Tv.Events; namespace NzbDrone.Core.Tv @@ -21,6 +22,8 @@ namespace NzbDrone.Core.Tv Series FindSeries(string title); void AddSeries(string title, string path, int tvDbSeriesId, int qualityProfileId, DateTime? airedAfter); void UpdateFromSeriesEditor(IList editedSeries); + Series FindByTvdbId(int tvdbId); + void SetSeriesType(int seriesId, SeriesType seriesType); } public class SeriesService : ISeriesService @@ -28,24 +31,22 @@ namespace NzbDrone.Core.Tv private readonly ISeriesRepository _seriesRepository; private readonly IConfigService _configService; private readonly TvDbProvider _tvDbProvider; - private readonly MetadataProvider _metadataProvider; private readonly TvRageMappingProvider _tvRageMappingProvider; private readonly IEventAggregator _eventAggregator; private readonly IQualityProfileService _qualityProfileService; private static readonly Logger logger = LogManager.GetCurrentClassLogger(); - private readonly SceneMappingProvider _sceneNameMappingProvider; + private readonly SceneMappingService _sceneNameMappingService; public SeriesService(ISeriesRepository seriesRepository, IConfigService configServiceService, - TvDbProvider tvDbProviderProvider, SceneMappingProvider sceneNameMappingProvider, MetadataProvider metadataProvider, + TvDbProvider tvDbProviderProvider, SceneMappingService sceneNameMappingService, TvRageMappingProvider tvRageMappingProvider, IEventAggregator eventAggregator, IQualityProfileService qualityProfileService) { _seriesRepository = seriesRepository; _configService = configServiceService; _tvDbProvider = tvDbProviderProvider; - _sceneNameMappingProvider = sceneNameMappingProvider; - _metadataProvider = metadataProvider; + _sceneNameMappingService = sceneNameMappingService; _tvRageMappingProvider = tvRageMappingProvider; _eventAggregator = eventAggregator; _qualityProfileService = qualityProfileService; @@ -91,7 +92,6 @@ namespace NzbDrone.Core.Tv } _seriesRepository.Update(series); - _metadataProvider.CreateForSeries(series, tvDbSeries); return series; } @@ -100,7 +100,7 @@ namespace NzbDrone.Core.Tv { var normalizeTitle = Parser.NormalizeTitle(title); - var mapping = _sceneNameMappingProvider.GetSeriesId(normalizeTitle); + var mapping = _sceneNameMappingService.GetTvDbId(normalizeTitle); if (mapping.HasValue) { var sceneSeries = _seriesRepository.Get(mapping.Value); @@ -159,6 +159,16 @@ namespace NzbDrone.Core.Tv } + public Series FindByTvdbId(int tvdbId) + { + return _seriesRepository.FindByTvdbId(tvdbId); + } + + public void SetSeriesType(int seriesId, SeriesType seriesType) + { + _seriesRepository.SetSeriesType(seriesId, seriesType); + } + /// /// Cleans up the AirsTime Component from TheTVDB since it can be garbage that comes in. /// diff --git a/NzbDrone.sln b/NzbDrone.sln index 8a3b10af3..6687c58ee 100644 --- a/NzbDrone.sln +++ b/NzbDrone.sln @@ -45,8 +45,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution JSLintOptions.xml = JSLintOptions.xml EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NzbDrone.SqlCe", "NzbDrone.SqlCe\NzbDrone.SqlCe.csproj", "{64E5482F-0C4F-46C6-9377-699D3EADBA9E}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NzbDrone.Backbone", "NzbDrone.Backbone\NzbDrone.Backbone.csproj", "{EE6B9BAC-2136-460A-87B0-709D2AC0A9AE}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Autofac.Integration.Mvc", "Autofac.Integration.Mvc\Autofac.Integration.Mvc.csproj", "{DD874E64-C7EC-464D-925F-CF4A709EDEEF}" @@ -320,24 +318,6 @@ Global {FD286DF8-2D3A-4394-8AD5-443FADE55FB2}.Services|Mixed Platforms.Build.0 = Release|Any CPU {FD286DF8-2D3A-4394-8AD5-443FADE55FB2}.Services|x64.ActiveCfg = Release|Any CPU {FD286DF8-2D3A-4394-8AD5-443FADE55FB2}.Services|x86.ActiveCfg = Release|Any CPU - {64E5482F-0C4F-46C6-9377-699D3EADBA9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {64E5482F-0C4F-46C6-9377-699D3EADBA9E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {64E5482F-0C4F-46C6-9377-699D3EADBA9E}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {64E5482F-0C4F-46C6-9377-699D3EADBA9E}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {64E5482F-0C4F-46C6-9377-699D3EADBA9E}.Debug|x64.ActiveCfg = Debug|Any CPU - {64E5482F-0C4F-46C6-9377-699D3EADBA9E}.Debug|x86.ActiveCfg = Debug|Any CPU - {64E5482F-0C4F-46C6-9377-699D3EADBA9E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {64E5482F-0C4F-46C6-9377-699D3EADBA9E}.Release|Any CPU.Build.0 = Release|Any CPU - {64E5482F-0C4F-46C6-9377-699D3EADBA9E}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {64E5482F-0C4F-46C6-9377-699D3EADBA9E}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {64E5482F-0C4F-46C6-9377-699D3EADBA9E}.Release|x64.ActiveCfg = Release|Any CPU - {64E5482F-0C4F-46C6-9377-699D3EADBA9E}.Release|x86.ActiveCfg = Release|Any CPU - {64E5482F-0C4F-46C6-9377-699D3EADBA9E}.Services|Any CPU.ActiveCfg = Release|Any CPU - {64E5482F-0C4F-46C6-9377-699D3EADBA9E}.Services|Any CPU.Build.0 = Release|Any CPU - {64E5482F-0C4F-46C6-9377-699D3EADBA9E}.Services|Mixed Platforms.ActiveCfg = Release|Any CPU - {64E5482F-0C4F-46C6-9377-699D3EADBA9E}.Services|Mixed Platforms.Build.0 = Release|Any CPU - {64E5482F-0C4F-46C6-9377-699D3EADBA9E}.Services|x64.ActiveCfg = Release|Any CPU - {64E5482F-0C4F-46C6-9377-699D3EADBA9E}.Services|x86.ActiveCfg = Release|Any CPU {EE6B9BAC-2136-460A-87B0-709D2AC0A9AE}.Debug|Any CPU.ActiveCfg = Release|Any CPU {EE6B9BAC-2136-460A-87B0-709D2AC0A9AE}.Debug|Any CPU.Build.0 = Release|Any CPU {EE6B9BAC-2136-460A-87B0-709D2AC0A9AE}.Debug|Mixed Platforms.ActiveCfg = Release|Any CPU diff --git a/NzbDrone.sln.DotSettings b/NzbDrone.sln.DotSettings index 38ec44874..ae9ad4e79 100644 --- a/NzbDrone.sln.DotSettings +++ b/NzbDrone.sln.DotSettings @@ -2,6 +2,7 @@ ERROR DO_NOT_SHOW DO_NOT_SHOW + DO_NOT_SHOW <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb"><ExtraRule Prefix="" Suffix="" Style="AaBb" /></Policy> BOTH_SIDES OUTLINE