blob: a880e66011150f3f7b65245058bdcce8c82c3174 (
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 InsertItem
{
/// <summary>
/// Null means use default value. Use <see cref="DbNullValue"/>.
/// </summary>
public InsertItem(string columnName, object? value)
{
ColumnName = columnName;
Value = value;
}
public string ColumnName { get; set; }
public object? Value { get; set; }
}
public interface IInsertClause : IClause
{
List<InsertItem> Items { get; }
string GenerateColumnListSql(string? dbProviderId = null);
(string sql, ParamList parameters) GenerateValueListSql(string? dbProviderId = null);
}
public class InsertClause : IInsertClause
{
public List<InsertItem> Items { get; } = new List<InsertItem>();
public InsertClause(params InsertItem[] items)
{
Items.AddRange(items);
}
public InsertClause Add(params InsertItem[] items)
{
Items.AddRange(items);
return this;
}
public InsertClause Add(string column, object? value)
{
return Add(new InsertItem(column, value));
}
public static InsertClause Create(params InsertItem[] items)
{
return new InsertClause(items);
}
public List<string> GetRelatedColumns()
{
return Items.Select(i => i.ColumnName).ToList();
}
public string GenerateColumnListSql(string? dbProviderId = null)
{
return string.Join(", ", Items.Select(i => i.ColumnName));
}
public (string sql, ParamList parameters) GenerateValueListSql(string? dbProviderId = null)
{
var parameters = new ParamList();
var sb = new StringBuilder();
for (var i = 0; i < Items.Count; i++)
{
var item = Items[i];
var parameterName = parameters.AddRandomNameParameter(item.Value, item.ColumnName);
sb.Append($"@{parameterName}");
if (i != Items.Count - 1)
sb.Append(", ");
}
return (sb.ToString(), parameters);
}
}
|