aboutsummaryrefslogtreecommitdiff
path: root/docker/crupest-api/CrupestApi/CrupestApi.Commons/Crud/UpdateClause.cs
blob: 0997656d3be271f42d9f3863e42e1f9ccc76b745 (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
76
77
78
79
80
81
82
83
84
85
86
using System.Text;
using Dapper;

namespace CrupestApi.Commons.Crud;

public class UpdateItem
{
    public UpdateItem(string columnName, object? value)
    {
        ColumnName = columnName;
        Value = value;
    }

    public UpdateItem(KeyValuePair<string, object?> pair)
    {
        ColumnName = pair.Key;
        Value = pair.Value;
    }

    public string ColumnName { get; set; }
    public object? Value { get; set; }

    public static implicit operator KeyValuePair<string, object?>(UpdateItem item)
    {
        return new(item.ColumnName, item.Value);
    }

    public static implicit operator UpdateItem(KeyValuePair<string, object?> pair)
    {
        return new(pair);
    }
}

public class UpdateClause
{
    public List<UpdateItem> Items { get; } = new List<UpdateItem>();

    public UpdateClause(IEnumerable<UpdateItem> items)
    {
        Items.AddRange(items);
    }

    public UpdateClause(params UpdateItem[] items)
    {
        Items.AddRange(items);
    }

    public UpdateClause Add(params UpdateItem[] items)
    {
        Items.AddRange(items);
        return this;
    }

    public UpdateClause Add(string column, object? value)
    {
        return Add(new UpdateItem(column, value));
    }

    public static UpdateClause Create(params UpdateItem[] items)
    {
        return new UpdateClause(items);
    }

    public List<string> GetRelatedColumns()
    {
        return Items.Select(i => i.ColumnName).ToList();
    }

    public string GenerateSql(DynamicParameters parameters)
    {
        StringBuilder result = new StringBuilder();

        foreach (var item in Items)
        {
            if (result.Length > 0)
            {
                result.Append(", ");
            }

            var parameterName = parameters.AddRandomNameParameter(item.Value);
            result.Append($"{item.ColumnName} = @{parameterName}");
        }

        return result.ToString();
    }
}