aboutsummaryrefslogtreecommitdiff
path: root/dropped/docker/crupest-api/CrupestApi/CrupestApi.Commons/Crud/DbConnectionFactory.cs
blob: 701622c2509dbed148e063f4ee0710141ae7fbec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System.Data;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Options;

namespace CrupestApi.Commons.Crud;

public interface IDbConnectionFactory
{
    IDbConnection Get(string? name = null);
    bool ShouldDisposeConnection { get; }
}

public class SqliteConnectionFactory : IDbConnectionFactory
{
    private readonly IOptionsMonitor<CrupestApiConfig> _apiConfigMonitor;

    public SqliteConnectionFactory(IOptionsMonitor<CrupestApiConfig> apiConfigMonitor)
    {
        _apiConfigMonitor = apiConfigMonitor;
    }

    public IDbConnection Get(string? name = null)
    {
        var connectionString = new SqliteConnectionStringBuilder()
        {
            DataSource = Path.Combine(_apiConfigMonitor.CurrentValue.DataDir, $"{name ?? "crupest-api"}.db"),
            Mode = SqliteOpenMode.ReadWriteCreate
        }.ToString();

        var connection = new SqliteConnection(connectionString);
        connection.Open();
        return connection;
    }

    public bool ShouldDisposeConnection => true;
}

public class SqliteMemoryConnectionFactory : IDbConnectionFactory, IDisposable
{
    private readonly Dictionary<string, IDbConnection> _connections = new();

    public IDbConnection Get(string? name = null)
    {
        name = name ?? "crupest-api";

        if (_connections.TryGetValue(name, out var connection))
        {
            return connection;
        }
        else
        {
            var connectionString = new SqliteConnectionStringBuilder()
            {
                DataSource = ":memory:",
                Mode = SqliteOpenMode.ReadWriteCreate
            }.ToString();

            connection = new SqliteConnection(connectionString);
            _connections.Add(name, connection);
            connection.Open();
            return connection;
        }
    }

    public bool ShouldDisposeConnection => false;


    public void Dispose()
    {
        foreach (var connection in _connections.Values)
        {
            connection.Dispose();
        }
    }
}