forked from optimajet/WorkflowEngine.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDbObject.cs
More file actions
225 lines (185 loc) · 8.18 KB
/
DbObject.cs
File metadata and controls
225 lines (185 loc) · 8.18 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Npgsql;
using NpgsqlTypes;
namespace OptimaJet.Workflow.PostgreSQL
{
public class ColumnInfo
{
public string Name;
public NpgsqlDbType Type = NpgsqlDbType.Varchar;
public bool IsKey = false;
public int Size = 256;
public bool IsVirtual = false;
}
public abstract class DbObject
{
public static string SchemaName { get; set; }
}
public class DbObject<T> : DbObject where T : DbObject<T>, new()
{
// ReSharper disable once StaticMemberInGenericType
public static string DbTableName;
public static string ObjectName => $"\"{SchemaName}\".\"{DbTableName}\"";
public List<ColumnInfo> DBColumns = new List<ColumnInfo>();
public virtual object GetValue(string key)
{
return null;
}
public virtual void SetValue(string key, object value)
{
}
#region Command Insert/Update/Delete/Commit
public int Insert(NpgsqlConnection connection)
{
return InsertAsync(connection).Result;
}
public Task<int> InsertAsync(NpgsqlConnection connection)
{
var commandText = string.Format("INSERT INTO {0} ({1}) VALUES ({2})",
ObjectName,
String.Join(",", DBColumns.Where(c=> !c.IsVirtual).Select(c => string.Format("\"{0}\"", c.Name))),
String.Join(",", DBColumns.Where(c => !c.IsVirtual).Select(c => "@" + c.Name)));
var parameters = DBColumns.Select(CreateParameter).ToArray();
return ExecuteCommandAsync(connection, commandText, parameters);
}
public int Update(NpgsqlConnection connection)
{
return UpdateAsync(connection).Result;
}
public Task<int> UpdateAsync(NpgsqlConnection connection)
{
string command = string.Format("UPDATE {0} SET {1} WHERE {2}",
ObjectName,
String.Join(",", DBColumns.Where(c => !c.IsVirtual).Where(c => !c.IsKey).Select(c => string.Format("\"{0}\" = @{0}", c.Name))),
String.Join(" AND ", DBColumns.Where(c => c.IsKey).Select(c => string.Format("\"{0}\" = @{0}", c.Name))));
var parameters = DBColumns.Select(CreateParameter).ToArray();
return ExecuteCommandAsync(connection, command, parameters);
}
public static T SelectByKey(NpgsqlConnection connection, object id)
{
return SelectByKeyAsync(connection, id).Result;
}
public static async Task<T> SelectByKeyAsync(NpgsqlConnection connection, object id)
{
var t = new T();
var key = t.DBColumns.FirstOrDefault(c => c.IsKey);
if(key == null)
{
throw new Exception($"Key for table {DbTableName} isn't defined.");
}
string selectText = $"SELECT * FROM {ObjectName} WHERE \"{key.Name}\" = @p_id";
var pId = new NpgsqlParameter("p_id", key.Type) {Value = id};
return (await SelectAsync(connection, selectText, pId).ConfigureAwait(false)).FirstOrDefault();
}
public static int Delete(NpgsqlConnection connection, object id, NpgsqlTransaction transaction = null)
{
return DeleteAsync(connection, id, transaction).Result;
}
public static Task<int> DeleteAsync(NpgsqlConnection connection, object id, NpgsqlTransaction transaction = null)
{
var t = new T();
var key = t.DBColumns.FirstOrDefault(c => c.IsKey);
if (key == null)
throw new Exception($"Key for table {DbTableName} isn't defined.");
var pId = new NpgsqlParameter("p_id", key.Type) {Value = id};
return ExecuteCommandAsync(connection, $"DELETE FROM {ObjectName} WHERE \"{key.Name}\" = @p_id", transaction, pId);
}
public static int ExecuteCommand(NpgsqlConnection connection, string commandText,
params NpgsqlParameter[] parameters)
{
return ExecuteCommand(connection, commandText, null, parameters);
}
public static Task<int> ExecuteCommandAsync(NpgsqlConnection connection, string commandText,
params NpgsqlParameter[] parameters)
{
return ExecuteCommandAsync(connection, commandText, null, parameters);
}
public static int ExecuteCommand(NpgsqlConnection connection, string commandText,NpgsqlTransaction transaction = null, params NpgsqlParameter[] parameters)
{
return ExecuteCommandAsync(connection, commandText, transaction, parameters).Result;
}
public static async Task<int> ExecuteCommandAsync(NpgsqlConnection connection, string commandText, NpgsqlTransaction transaction = null,
params NpgsqlParameter[] parameters)
{
if (connection.State != ConnectionState.Open)
{
await connection.OpenAsync().ConfigureAwait(false);
}
using (var command = connection.CreateCommand())
{
command.Connection = connection;
if (transaction != null)
{
command.Transaction = transaction;
}
command.CommandText = commandText;
command.CommandType = CommandType.Text;
command.Parameters.AddRange(parameters);
var cnt = await command.ExecuteNonQueryAsync().ConfigureAwait(false);
return cnt;
}
}
public static T[] Select(NpgsqlConnection connection, string commandText, params NpgsqlParameter[] parameters)
{
return SelectAsync(connection, commandText, parameters).Result;
}
public static async Task<T[]> SelectAsync(NpgsqlConnection connection, string commandText, params NpgsqlParameter[] parameters)
{
if (connection.State != ConnectionState.Open)
{
await connection.OpenAsync().ConfigureAwait(false);
}
using (var command = connection.CreateCommand())
{
command.Connection = connection;
command.CommandText = commandText;
command.CommandType = CommandType.Text;
command.Parameters.AddRange(parameters);
var res = new List<T>();
using (var reader = await command.ExecuteReaderAsync().ConfigureAwait(false))
{
while (await reader.ReadAsync().ConfigureAwait(false))
{
T item = new T();
for (int i = 0; i < reader.FieldCount; i++)
{
var name = reader.GetName(i);
var column = item.DBColumns.FirstOrDefault(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
if (column != null)
{
item.SetValue(column.Name, reader.IsDBNull(i) ? null : reader.GetValue(i));
}
}
res.Add(item);
}
}
return res.ToArray();
}
}
#endregion
public virtual NpgsqlParameter CreateParameter(ColumnInfo c)
{
var value = GetValue(c.Name);
var isNullable = IsNullable(value);
if (isNullable && value == null)
{
value = DBNull.Value;
}
var p = new NpgsqlParameter(c.Name, c.Type) {Value = value, IsNullable = isNullable};
return p;
}
private static bool IsNullable<T1>(T1 obj)
{
if (obj == null) return true; //-V3111
Type type = typeof(T1);
if (!type.GetTypeInfo().IsValueType) return true;
if (Nullable.GetUnderlyingType(type) != null) return true;
return false;
}
}
}