//----------------------------------------------------------------------- // // Copyright (c) lanedirt. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // //----------------------------------------------------------------------- namespace AliasServerDb; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; /// /// SQLite implementation of the AliasServerDbContext. /// public class AliasServerDbContextSqlite : AliasServerDbContext { /// /// Initializes a new instance of the class. /// public AliasServerDbContextSqlite() { SetPragmaSettings(); } /// /// Initializes a new instance of the class. /// /// DbContextOptions. public AliasServerDbContextSqlite(DbContextOptions options) : base(options) { SetPragmaSettings(); } /// /// The OnModelCreating method. /// /// ModelBuilder instance. protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // Set TEXT as default column type for string properties because // SQLite does not support varchar(max). foreach (var entity in modelBuilder.Model.GetEntityTypes()) { foreach (var property in entity.GetProperties()) { // SQLite does not support varchar(max) so we use TEXT. if (property.ClrType == typeof(string) && property.GetMaxLength() == null) { property.SetColumnType("TEXT"); } } } } /// /// Sets up the connection string if it is not already configured. /// /// DbContextOptionsBuilder instance. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (optionsBuilder.IsConfigured) { return; } var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .Build(); // Add SQLite connection with enhanced settings var connectionString = configuration.GetConnectionString("AliasServerDbContext") + ";Mode=ReadWriteCreate;Cache=Shared"; optionsBuilder .UseSqlite(connectionString, options => options.CommandTimeout(60)) .UseLazyLoadingProxies(); } /// /// Sets up the PRAGMA settings for SQLite. /// private void SetPragmaSettings() { var connection = Database.GetDbConnection(); if (connection.State != System.Data.ConnectionState.Open) { connection.Open(); } using (var command = connection.CreateCommand()) { // Increase busy timeout command.CommandText = @" PRAGMA busy_timeout = 30000; PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA temp_store = MEMORY; PRAGMA mmap_size = 1073741824;"; command.ExecuteNonQuery(); } } }