AuthorBuddy/Data/AppDbContext.cs
2026-05-14 12:31:35 +02:00

89 lines
3.2 KiB
C#

using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace AuthorBuddy.Web.Data;
public class AppDbContext : DbContext
{
public DbSet<ProjectEntity> Projects => Set<ProjectEntity>();
public DbSet<SettingEntity> Settings => Set<SettingEntity>();
public DbSet<DocumentMetaEntity> DocumentMeta => Set<DocumentMetaEntity>();
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ProjectEntity>(entity =>
{
entity.ToTable("Projects");
entity.HasKey(e => e.Id);
entity.Property(e => e.Name).IsRequired();
entity.Property(e => e.RootPath).IsRequired();
entity.Property(e => e.LastOpened).HasColumnName("last_opened");
});
modelBuilder.Entity<SettingEntity>(entity =>
{
entity.ToTable("Settings");
entity.HasKey(e => e.Key);
entity.Property(e => e.Key).HasColumnName("key");
entity.Property(e => e.Value).HasColumnName("value").IsRequired();
});
modelBuilder.Entity<DocumentMetaEntity>(entity =>
{
entity.ToTable("DocumentMeta");
entity.HasKey(e => e.Id);
entity.Property(e => e.FilePath).HasColumnName("file_path").IsRequired();
entity.Property(e => e.LastModified).HasColumnName("last_modified");
entity.Property(e => e.FileType).HasColumnName("file_type");
entity.Property(e => e.ProjectId).HasColumnName("project_id");
});
}
public static void InitializeDatabase(string connectionString)
{
using var connection = new SqliteConnection(connectionString);
connection.Open();
connection.EnableExtensions(true);
try
{
connection.LoadExtension("vec0");
using var testCmd = connection.CreateCommand();
testCmd.CommandText = "SELECT vec_version();";
var version = testCmd.ExecuteScalar();
Console.WriteLine($"sqlite-vec Version: {version}");
}
catch (SqliteException ex)
{
Console.WriteLine($"Fehler beim Laden von vec0: {ex.Message}");
}
using var createVecCmd = connection.CreateCommand();
createVecCmd.CommandText = @"
CREATE TABLE IF NOT EXISTS Projects (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
root_path TEXT NOT NULL,
last_opened DATETIME
);
CREATE TABLE IF NOT EXISTS Settings (
key TEXT NOT NULL UNIQUE,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS DocumentMeta (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER,
file_path TEXT UNIQUE,
last_modified DATETIME,
hash TEXT,
file_type TEXT,
FOREIGN KEY(project_id) REFERENCES Projects(id)
);
CREATE VIRTUAL TABLE IF NOT EXISTS vec_documents USING vec0(
embedding float[1024]
);";
createVecCmd.ExecuteNonQuery();
}
}