aboutsummaryrefslogtreecommitdiff
path: root/dropped/docker/crupest-api/CrupestApi/CrupestApi.Commons/Crud/UpdateClause.cs
blob: de5c6c3196d3d8f86fac4ef18a5c3db61570e2a3 (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
using System.Text;

namespace CrupestApi.Commons.Crud;

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

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

public interface IUpdateClause : IClause
{
    List<UpdateItem> Items { get; }
    (string sql, ParamList parameters) GenerateSql();
}

public class UpdateClause : IUpdateClause
{
    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 sql, ParamList parameters) GenerateSql()
    {
        var parameters = new ParamList();

        StringBuilder result = new StringBuilder();

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

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

        return (result.ToString(), parameters);
    }
}