Merge branch 'j.lechner/sqlite-database' into 'main'

feat: add SQLite song database and repository

Closes #2

See merge request julian/blockwoche3.1-radiosender!2
This commit is contained in:
Julian Lechner committed 2026-11-23 09:08:18 +00:00
commit 89b7959404
10 files changed
+315

No files matched your search

+3
View File
@@ -12,8 +12,11 @@ WPF desktop app that plans and plays a radio program: random music from a SQLite
```powershell ```powershell
dotnet build Radiosender.slnx dotnet build Radiosender.slnx
dotnet run --project src/Radiosender dotnet run --project src/Radiosender
dotnet test Radiosender.slnx
``` ```
The app creates its SQLite database on first start at `%LOCALAPPDATA%\Radiosender\radiosender.db`.
## Structure ## Structure
The app uses the MVC pattern and [WPF UI](https://github.com/lepoco/wpfui) for the interface. The app uses the MVC pattern and [WPF UI](https://github.com/lepoco/wpfui) for the interface.
+3
View File
@@ -2,4 +2,7 @@
<Folder Name="/src/"> <Folder Name="/src/">
<Project Path="src/Radiosender/Radiosender.csproj" /> <Project Path="src/Radiosender/Radiosender.csproj" />
</Folder> </Folder>
<Folder Name="/tests/">
<Project Path="tests/Radiosender.Tests/Radiosender.Tests.csproj" />
</Folder>
</Solution> </Solution>
+9
View File
@@ -1,7 +1,16 @@
using System.Windows; using System.Windows;
using Radiosender.Services;
namespace Radiosender; namespace Radiosender;
public partial class App : Application public partial class App : Application
{ {
public static SongRepository Songs { get; private set; } = null!;
protected override void OnStartup(StartupEventArgs e)
{
// Creates the database file and table on first start.
Songs = new SongRepository(SongRepository.DefaultDatabasePath);
base.OnStartup(e);
}
} }
View File
Whitespace-only changes.
+19
View File
@@ -0,0 +1,19 @@
namespace Radiosender.Models;
public enum SongSource
{
Upload,
Openverse,
}
public class Song
{
public long Id { get; set; }
public string Title { get; set; } = "";
public string Artist { get; set; } = "";
public TimeSpan Duration { get; set; }
public string FilePath { get; set; } = "";
public SongSource Source { get; set; }
public string? License { get; set; }
public string? Attribution { get; set; }
}
+1
View File
@@ -9,6 +9,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.15" />
<PackageReference Include="WPF-UI" Version="4.3.0" /> <PackageReference Include="WPF-UI" Version="4.3.0" />
</ItemGroup> </ItemGroup>
View File
Whitespace-only changes.
+128
View File
@@ -0,0 +1,128 @@
using System.IO;
using Microsoft.Data.Sqlite;
using Radiosender.Models;
namespace Radiosender.Services;
public class SongRepository
{
public static string DefaultDatabasePath { get; } = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Radiosender", "radiosender.db");
private const string Columns = "Id, Title, Artist, DurationMs, FilePath, Source, License, Attribution";
private readonly string _connectionString;
public SongRepository(string databasePath)
{
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(databasePath))!);
_connectionString = new SqliteConnectionStringBuilder { DataSource = databasePath }.ToString();
using var connection = Open();
using var command = connection.CreateCommand();
command.CommandText = """
CREATE TABLE IF NOT EXISTS Songs (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Title TEXT NOT NULL,
Artist TEXT NOT NULL,
DurationMs INTEGER NOT NULL CHECK (DurationMs > 0),
FilePath TEXT NOT NULL,
Source INTEGER NOT NULL,
License TEXT,
Attribution TEXT
)
""";
command.ExecuteNonQuery();
}
public IReadOnlyList<Song> GetAll()
{
using var connection = Open();
using var command = connection.CreateCommand();
command.CommandText = $"SELECT {Columns} FROM Songs ORDER BY Artist, Title";
using var reader = command.ExecuteReader();
var songs = new List<Song>();
while (reader.Read())
songs.Add(Read(reader));
return songs;
}
public Song? GetById(long id)
{
using var connection = Open();
using var command = connection.CreateCommand();
command.CommandText = $"SELECT {Columns} FROM Songs WHERE Id = $id";
command.Parameters.AddWithValue("$id", id);
using var reader = command.ExecuteReader();
return reader.Read() ? Read(reader) : null;
}
/// <summary>Inserts the song and sets its <see cref="Song.Id"/>.</summary>
public void Add(Song song)
{
using var connection = Open();
using var command = connection.CreateCommand();
command.CommandText = """
INSERT INTO Songs (Title, Artist, DurationMs, FilePath, Source, License, Attribution)
VALUES ($title, $artist, $durationMs, $filePath, $source, $license, $attribution);
SELECT last_insert_rowid();
""";
AddParameters(command, song);
song.Id = (long)command.ExecuteScalar()!;
}
/// <returns><c>false</c> if no song with this id exists.</returns>
public bool Update(Song song)
{
using var connection = Open();
using var command = connection.CreateCommand();
command.CommandText = """
UPDATE Songs SET Title = $title, Artist = $artist, DurationMs = $durationMs, FilePath = $filePath,
Source = $source, License = $license, Attribution = $attribution
WHERE Id = $id
""";
AddParameters(command, song);
command.Parameters.AddWithValue("$id", song.Id);
return command.ExecuteNonQuery() == 1;
}
/// <returns><c>false</c> if no song with this id exists.</returns>
public bool Delete(long id)
{
using var connection = Open();
using var command = connection.CreateCommand();
command.CommandText = "DELETE FROM Songs WHERE Id = $id";
command.Parameters.AddWithValue("$id", id);
return command.ExecuteNonQuery() == 1;
}
private SqliteConnection Open()
{
var connection = new SqliteConnection(_connectionString);
connection.Open();
return connection;
}
private static void AddParameters(SqliteCommand command, Song song)
{
command.Parameters.AddWithValue("$title", song.Title);
command.Parameters.AddWithValue("$artist", song.Artist);
command.Parameters.AddWithValue("$durationMs", (long)song.Duration.TotalMilliseconds);
command.Parameters.AddWithValue("$filePath", song.FilePath);
command.Parameters.AddWithValue("$source", (int)song.Source);
command.Parameters.AddWithValue("$license", (object?)song.License ?? DBNull.Value);
command.Parameters.AddWithValue("$attribution", (object?)song.Attribution ?? DBNull.Value);
}
private static Song Read(SqliteDataReader reader) => new()
{
Id = reader.GetInt64(0),
Title = reader.GetString(1),
Artist = reader.GetString(2),
Duration = TimeSpan.FromMilliseconds(reader.GetInt64(3)),
FilePath = reader.GetString(4),
Source = (SongSource)reader.GetInt32(5),
License = reader.IsDBNull(6) ? null : reader.GetString(6),
Attribution = reader.IsDBNull(7) ? null : reader.GetString(7),
};
}
@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.4" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Radiosender\Radiosender.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,127 @@
using Microsoft.Data.Sqlite;
using Radiosender.Models;
using Radiosender.Services;
namespace Radiosender.Tests;
public sealed class SongRepositoryTests : IDisposable
{
private readonly string _directory = Path.Combine(Path.GetTempPath(), "radiosender-tests", Guid.NewGuid().ToString("N"));
private string DatabasePath => Path.Combine(_directory, "test.db");
public void Dispose()
{
SqliteConnection.ClearAllPools(); // pooled connections keep the file locked
Directory.Delete(_directory, recursive: true);
}
private static Song NewSong(string title = "Song") => new()
{
Title = title,
Artist = "Artist",
Duration = TimeSpan.FromSeconds(185.5),
FilePath = @"C:\music\song.mp3",
Source = SongSource.Openverse,
License = "CC BY 4.0",
Attribution = null,
};
[Fact]
public void Constructor_CreatesDatabaseFileAndDirectory()
{
_ = new SongRepository(DatabasePath);
Assert.True(File.Exists(DatabasePath));
}
[Fact]
public void Add_ThenGetById_ReturnsSameValues()
{
var repository = new SongRepository(DatabasePath);
var song = NewSong();
repository.Add(song);
var loaded = repository.GetById(song.Id);
Assert.True(song.Id > 0);
Assert.NotNull(loaded);
Assert.Equal(song.Title, loaded.Title);
Assert.Equal(song.Artist, loaded.Artist);
Assert.Equal(song.Duration, loaded.Duration);
Assert.Equal(song.FilePath, loaded.FilePath);
Assert.Equal(song.Source, loaded.Source);
Assert.Equal(song.License, loaded.License);
Assert.Null(loaded.Attribution);
}
[Fact]
public void Data_SurvivesNewRepositoryInstance()
{
new SongRepository(DatabasePath).Add(NewSong("A"));
var songs = new SongRepository(DatabasePath).GetAll();
Assert.Equal("A", Assert.Single(songs).Title);
}
[Fact]
public void Update_ChangesStoredSong()
{
var repository = new SongRepository(DatabasePath);
var song = NewSong();
repository.Add(song);
song.Title = "Renamed";
song.Attribution = "by someone";
Assert.True(repository.Update(song));
var loaded = repository.GetById(song.Id)!;
Assert.Equal("Renamed", loaded.Title);
Assert.Equal("by someone", loaded.Attribution);
}
[Fact]
public void Delete_RemovesSong()
{
var repository = new SongRepository(DatabasePath);
var song = NewSong();
repository.Add(song);
Assert.True(repository.Delete(song.Id));
Assert.Null(repository.GetById(song.Id));
Assert.Empty(repository.GetAll());
}
[Fact]
public void UpdateAndDelete_ReturnFalseForUnknownId()
{
var repository = new SongRepository(DatabasePath);
var unknown = NewSong();
unknown.Id = 42;
Assert.False(repository.Update(unknown));
Assert.False(repository.Delete(42));
}
[Fact]
public void Add_StoresTitleWithSqlCharactersAsText()
{
var repository = new SongRepository(DatabasePath);
var song = NewSong("x'); DROP TABLE Songs; --");
repository.Add(song);
Assert.Equal(song.Title, Assert.Single(repository.GetAll()).Title);
}
[Fact]
public void Add_RejectsZeroDuration()
{
var repository = new SongRepository(DatabasePath);
var song = NewSong();
song.Duration = TimeSpan.Zero;
Assert.Throws<SqliteException>(() => repository.Add(song));
}
}