| | 1 | | using System; |
| | 2 | | using System.Collections.Generic; |
| | 3 | | using System.Globalization; |
| | 4 | | using System.IO; |
| | 5 | | using System.Linq; |
| | 6 | | using System.Threading; |
| | 7 | | using System.Threading.Tasks; |
| | 8 | | using Jellyfin.Database.Implementations; |
| | 9 | | using Jellyfin.Database.Implementations.DbConfiguration; |
| | 10 | | using MediaBrowser.Common.Configuration; |
| | 11 | | using Microsoft.Data.Sqlite; |
| | 12 | | using Microsoft.EntityFrameworkCore; |
| | 13 | | using Microsoft.EntityFrameworkCore.Diagnostics; |
| | 14 | | using Microsoft.Extensions.Logging; |
| | 15 | |
|
| | 16 | | namespace Jellyfin.Database.Providers.Sqlite; |
| | 17 | |
|
| | 18 | | /// <summary> |
| | 19 | | /// Configures jellyfin to use an SQLite database. |
| | 20 | | /// </summary> |
| | 21 | | [JellyfinDatabaseProviderKey("Jellyfin-SQLite")] |
| | 22 | | public sealed class SqliteDatabaseProvider : IJellyfinDatabaseProvider |
| | 23 | | { |
| | 24 | | private const string BackupFolderName = "SQLiteBackups"; |
| | 25 | | private readonly IApplicationPaths _applicationPaths; |
| | 26 | | private readonly ILogger<SqliteDatabaseProvider> _logger; |
| | 27 | |
|
| | 28 | | /// <summary> |
| | 29 | | /// Initializes a new instance of the <see cref="SqliteDatabaseProvider"/> class. |
| | 30 | | /// </summary> |
| | 31 | | /// <param name="applicationPaths">Service to construct the fallback when the old data path configuration is used.</ |
| | 32 | | /// <param name="logger">A logger.</param> |
| | 33 | | public SqliteDatabaseProvider(IApplicationPaths applicationPaths, ILogger<SqliteDatabaseProvider> logger) |
| | 34 | | { |
| 43 | 35 | | _applicationPaths = applicationPaths; |
| 43 | 36 | | _logger = logger; |
| 43 | 37 | | } |
| | 38 | |
|
| | 39 | | /// <inheritdoc/> |
| | 40 | | public IDbContextFactory<JellyfinDbContext>? DbContextFactory { get; set; } |
| | 41 | |
|
| | 42 | | /// <inheritdoc/> |
| | 43 | | public void Initialise(DbContextOptionsBuilder options, DatabaseConfigurationOptions databaseConfiguration) |
| | 44 | | { |
| | 45 | | static T? GetOption<T>(ICollection<CustomDatabaseOption>? options, string key, Func<string, T> converter, Func<T |
| | 46 | | { |
| | 47 | | if (options is null) |
| | 48 | | { |
| | 49 | | return defaultValue is not null ? defaultValue() : default; |
| | 50 | | } |
| | 51 | |
|
| | 52 | | var value = options.FirstOrDefault(e => e.Key.Equals(key, StringComparison.OrdinalIgnoreCase)); |
| | 53 | | if (value is null) |
| | 54 | | { |
| | 55 | | return defaultValue is not null ? defaultValue() : default; |
| | 56 | | } |
| | 57 | |
|
| | 58 | | return converter(value.Value); |
| | 59 | | } |
| | 60 | |
|
| 42 | 61 | | var customOptions = databaseConfiguration.CustomProviderOptions?.Options; |
| | 62 | |
|
| 42 | 63 | | var sqliteConnectionBuilder = new SqliteConnectionStringBuilder(); |
| 42 | 64 | | sqliteConnectionBuilder.DataSource = Path.Combine(_applicationPaths.DataPath, "jellyfin.db"); |
| 42 | 65 | | sqliteConnectionBuilder.Cache = GetOption(customOptions, "cache", Enum.Parse<SqliteCacheMode>, () => SqliteCache |
| 42 | 66 | | sqliteConnectionBuilder.Pooling = GetOption(customOptions, "pooling", e => e.Equals(bool.TrueString, StringCompa |
| | 67 | |
|
| 42 | 68 | | var connectionString = sqliteConnectionBuilder.ToString(); |
| | 69 | |
|
| | 70 | | // Log SQLite connection parameters |
| 42 | 71 | | _logger.LogInformation("SQLite connection string: {ConnectionString}", connectionString); |
| | 72 | |
|
| 42 | 73 | | options |
| 42 | 74 | | .UseSqlite( |
| 42 | 75 | | connectionString, |
| 42 | 76 | | sqLiteOptions => sqLiteOptions.MigrationsAssembly(GetType().Assembly)) |
| 42 | 77 | | // TODO: Remove when https://github.com/dotnet/efcore/pull/35873 is merged & released |
| 42 | 78 | | .ConfigureWarnings(warnings => |
| 42 | 79 | | warnings.Ignore(RelationalEventId.NonTransactionalMigrationOperationWarning)) |
| 42 | 80 | | .AddInterceptors(new PragmaConnectionInterceptor( |
| 42 | 81 | | _logger, |
| 42 | 82 | | GetOption<int?>(customOptions, "cacheSize", e => int.Parse(e, CultureInfo.InvariantCulture)), |
| 42 | 83 | | GetOption(customOptions, "lockingmode", e => e, () => "NORMAL")!, |
| 42 | 84 | | GetOption(customOptions, "journalsizelimit", int.Parse, () => 134_217_728), |
| 42 | 85 | | GetOption(customOptions, "tempstoremode", int.Parse, () => 2), |
| 42 | 86 | | GetOption(customOptions, "syncmode", int.Parse, () => 1), |
| 42 | 87 | | customOptions?.Where(e => e.Key.StartsWith("#PRAGMA:", StringComparison.OrdinalIgnoreCase)).ToDictionary |
| | 88 | |
|
| 42 | 89 | | var enableSensitiveDataLogging = GetOption(customOptions, "EnableSensitiveDataLogging", e => e.Equals(bool.TrueS |
| 42 | 90 | | if (enableSensitiveDataLogging) |
| | 91 | | { |
| 0 | 92 | | options.EnableSensitiveDataLogging(enableSensitiveDataLogging); |
| 0 | 93 | | _logger.LogInformation("EnableSensitiveDataLogging is enabled on SQLite connection"); |
| | 94 | | } |
| 42 | 95 | | } |
| | 96 | |
|
| | 97 | | /// <inheritdoc/> |
| | 98 | | public async Task RunScheduledOptimisation(CancellationToken cancellationToken) |
| | 99 | | { |
| | 100 | | var context = await DbContextFactory!.CreateDbContextAsync(cancellationToken).ConfigureAwait(false); |
| | 101 | | await using (context.ConfigureAwait(false)) |
| | 102 | | { |
| | 103 | | await context.Database.ExecuteSqlRawAsync("PRAGMA wal_checkpoint(TRUNCATE)", cancellationToken).ConfigureAwa |
| | 104 | | await context.Database.ExecuteSqlRawAsync("PRAGMA optimize", cancellationToken).ConfigureAwait(false); |
| | 105 | | await context.Database.ExecuteSqlRawAsync("VACUUM", cancellationToken).ConfigureAwait(false); |
| | 106 | | await context.Database.ExecuteSqlRawAsync("PRAGMA wal_checkpoint(TRUNCATE)", cancellationToken).ConfigureAwa |
| | 107 | | _logger.LogInformation("jellyfin.db optimized successfully!"); |
| | 108 | | } |
| | 109 | | } |
| | 110 | |
|
| | 111 | | /// <inheritdoc/> |
| | 112 | | public void OnModelCreating(ModelBuilder modelBuilder) |
| | 113 | | { |
| 2 | 114 | | modelBuilder.SetDefaultDateTimeKind(DateTimeKind.Utc); |
| 2 | 115 | | } |
| | 116 | |
|
| | 117 | | /// <inheritdoc/> |
| | 118 | | public async Task RunShutdownTask(CancellationToken cancellationToken) |
| | 119 | | { |
| | 120 | | if (DbContextFactory is null) |
| | 121 | | { |
| | 122 | | return; |
| | 123 | | } |
| | 124 | |
|
| | 125 | | // Run before disposing the application |
| | 126 | | var context = await DbContextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false); |
| | 127 | | await using (context.ConfigureAwait(false)) |
| | 128 | | { |
| | 129 | | await context.Database.ExecuteSqlRawAsync("PRAGMA optimize", cancellationToken).ConfigureAwait(false); |
| | 130 | | } |
| | 131 | |
|
| | 132 | | SqliteConnection.ClearAllPools(); |
| | 133 | | } |
| | 134 | |
|
| | 135 | | /// <inheritdoc/> |
| | 136 | | public void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) |
| | 137 | | { |
| 2 | 138 | | configurationBuilder.Conventions.Add(_ => new DoNotUseReturningClauseConvention()); |
| 2 | 139 | | } |
| | 140 | |
|
| | 141 | | /// <inheritdoc /> |
| | 142 | | public Task<string> MigrationBackupFast(CancellationToken cancellationToken) |
| | 143 | | { |
| 0 | 144 | | var key = DateTime.UtcNow.ToString("yyyyMMddhhmmss", CultureInfo.InvariantCulture); |
| 0 | 145 | | var path = Path.Combine(_applicationPaths.DataPath, "jellyfin.db"); |
| 0 | 146 | | var backupFile = Path.Combine(_applicationPaths.DataPath, BackupFolderName); |
| 0 | 147 | | Directory.CreateDirectory(backupFile); |
| | 148 | |
|
| 0 | 149 | | backupFile = Path.Combine(backupFile, $"{key}_jellyfin.db"); |
| 0 | 150 | | File.Copy(path, backupFile); |
| 0 | 151 | | return Task.FromResult(key); |
| | 152 | | } |
| | 153 | |
|
| | 154 | | /// <inheritdoc /> |
| | 155 | | public Task RestoreBackupFast(string key, CancellationToken cancellationToken) |
| | 156 | | { |
| | 157 | | // ensure there are absolutly no dangling Sqlite connections. |
| 0 | 158 | | SqliteConnection.ClearAllPools(); |
| 0 | 159 | | var path = Path.Combine(_applicationPaths.DataPath, "jellyfin.db"); |
| 0 | 160 | | var backupFile = Path.Combine(_applicationPaths.DataPath, BackupFolderName, $"{key}_jellyfin.db"); |
| | 161 | |
|
| 0 | 162 | | if (!File.Exists(backupFile)) |
| | 163 | | { |
| 0 | 164 | | _logger.LogCritical("Tried to restore a backup that does not exist: {Key}", key); |
| 0 | 165 | | return Task.CompletedTask; |
| | 166 | | } |
| | 167 | |
|
| 0 | 168 | | File.Copy(backupFile, path, true); |
| 0 | 169 | | return Task.CompletedTask; |
| | 170 | | } |
| | 171 | |
|
| | 172 | | /// <inheritdoc /> |
| | 173 | | public Task DeleteBackup(string key) |
| | 174 | | { |
| 0 | 175 | | var backupFile = Path.Combine(_applicationPaths.DataPath, BackupFolderName, $"{key}_jellyfin.db"); |
| | 176 | |
|
| 0 | 177 | | if (!File.Exists(backupFile)) |
| | 178 | | { |
| 0 | 179 | | _logger.LogCritical("Tried to delete a backup that does not exist: {Key}", key); |
| 0 | 180 | | return Task.CompletedTask; |
| | 181 | | } |
| | 182 | |
|
| 0 | 183 | | File.Delete(backupFile); |
| 0 | 184 | | return Task.CompletedTask; |
| | 185 | | } |
| | 186 | |
|
| | 187 | | /// <inheritdoc/> |
| | 188 | | public async Task PurgeDatabase(JellyfinDbContext dbContext, IEnumerable<string>? tableNames) |
| | 189 | | { |
| | 190 | | ArgumentNullException.ThrowIfNull(tableNames); |
| | 191 | |
|
| | 192 | | var deleteQueries = new List<string>(); |
| | 193 | | foreach (var tableName in tableNames) |
| | 194 | | { |
| | 195 | | deleteQueries.Add($"DELETE FROM \"{tableName}\";"); |
| | 196 | | } |
| | 197 | |
|
| | 198 | | var deleteAllQuery = |
| | 199 | | $""" |
| | 200 | | PRAGMA foreign_keys = OFF; |
| | 201 | | {string.Join('\n', deleteQueries)} |
| | 202 | | PRAGMA foreign_keys = ON; |
| | 203 | | """; |
| | 204 | |
|
| | 205 | | await dbContext.Database.ExecuteSqlRawAsync(deleteAllQuery).ConfigureAwait(false); |
| | 206 | | } |
| | 207 | | } |