forked from NpgsqlRest/NpgsqlRest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExcelUploadHandler.cs
More file actions
370 lines (330 loc) · 13.9 KB
/
Copy pathExcelUploadHandler.cs
File metadata and controls
370 lines (330 loc) · 13.9 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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
using System.Text;
using ExcelDataReader;
using Npgsql;
using NpgsqlRest;
using NpgsqlRest.UploadHandlers;
using NpgsqlRest.UploadHandlers.Handlers;
using NpgsqlTypes;
using static NpgsqlRest.NpgsqlRestOptions;
namespace NpgsqlRestClient;
public class ExcelUploadOptions
{
private static readonly ExcelUploadOptions _instance = new();
public static ExcelUploadOptions Instance => _instance;
public string? ExcelSheetName { get; set; } = null;
public bool ExcelAllSheets { get; set; } = false;
public string ExcelTimeFormat { get; set; } = "HH:mm:ss";
public string ExcelDateFormat { get; set; } = "yyyy-MM-dd";
public string ExcelDateTimeFormat { get; set; } = "yyyy-MM-dd HH:mm:ss";
public bool ExcelRowDataAsJson { get; set; } = false;
public string ExcelUploadRowCommand { get; set; } = "call process_excel_row($1,$2,$3,$4)";
}
public class ExcelUploadHandler(
NpgsqlRestUploadOptions options,
RetryStrategy? cmdRetryStrategy) : BaseUploadHandler, IUploadHandler
{
private const string SheetNameParam = "sheet_name";
private const string AllSheetsParam = "all_sheets";
private const string TimeFormatParam = "time_format";
private const string DateFormatParam = "date_format";
private const string DateTimeFormatParam = "datetime_format";
private const string JsonRowDataParam = "row_is_json";
private const string RowCommandParam = "row_command";
protected override IEnumerable<string> GetParameters()
{
yield return IncludedMimeTypeParam;
yield return ExcludedMimeTypeParam;
yield return SheetNameParam;
yield return AllSheetsParam;
yield return TimeFormatParam;
yield return DateFormatParam;
yield return DateTimeFormatParam;
yield return JsonRowDataParam;
yield return RowCommandParam;
}
public bool RequiresTransaction => true;
private string _timeFormat = default!;
private string _dateFormat = default!;
private string _dateTimeFormat = default!;
public async Task<string> UploadAsync(NpgsqlConnection connection, HttpContext context, Dictionary<string, string>? parameters, CancellationToken cancellationToken = default)
{
string? targetSheetName = ExcelUploadOptions.Instance.ExcelSheetName;
bool allSheets = ExcelUploadOptions.Instance.ExcelAllSheets;
bool dataAsJson = ExcelUploadOptions.Instance.ExcelRowDataAsJson;
string rowCommand = ExcelUploadOptions.Instance.ExcelUploadRowCommand;
_timeFormat = ExcelUploadOptions.Instance.ExcelTimeFormat;
_dateFormat = ExcelUploadOptions.Instance.ExcelDateFormat;
_dateTimeFormat = ExcelUploadOptions.Instance.ExcelDateTimeFormat;
if (parameters is not null)
{
if (TryGetParam(parameters, SheetNameParam, out var sheetNameStr))
{
targetSheetName = sheetNameStr;
}
if (TryGetParam(parameters, AllSheetsParam, out var allSheetsStr) && bool.TryParse(allSheetsStr, out var allSheetsParsed))
{
allSheets = allSheetsParsed;
}
if (TryGetParam(parameters, TimeFormatParam, out var timeFormatStr))
{
_timeFormat = timeFormatStr;
}
if (TryGetParam(parameters, DateFormatParam, out var dateFormatStr))
{
_dateFormat = dateFormatStr;
}
if (TryGetParam(parameters, DateTimeFormatParam, out var dateTimeFormatStr))
{
_dateTimeFormat = dateTimeFormatStr;
}
if (TryGetParam(parameters, JsonRowDataParam, out var dataAsJsonStr) && bool.TryParse(dataAsJsonStr, out var dataAsJsonParsed))
{
dataAsJson = dataAsJsonParsed;
}
if (TryGetParam(parameters, RowCommandParam, out var rowCommandStr))
{
rowCommand = rowCommandStr;
}
}
if (options.LogUploadParameters is true)
{
Logger?.LogTrace("Upload for Excel: includedMimeTypePatterns={includedMimeTypePatterns}, excludedMimeTypePatterns={excludedMimeTypePatterns}, targetSheetName={targetSheetName}, allSheets={allSheets}, timeFormat={timeFormat}, dateFormat={dateFormat}, dateTimeFormat={dateTimeFormat}, rowCommand={rowCommand}",
IncludedMimeTypePatterns, ExcludedMimeTypePatterns, targetSheetName, allSheets, _timeFormat, _dateFormat, _dateTimeFormat, rowCommand);
}
using var command = new NpgsqlCommand(rowCommand, connection);
var paramCount = rowCommand.PgCountParams();
if (paramCount >= 1) command.Parameters.Add(NpgsqlRestParameter.CreateParamWithType(NpgsqlDbType.Integer));
if (paramCount >= 2)
{
if (dataAsJson is true)
{
command.Parameters.Add(NpgsqlRestParameter.CreateParamWithType(NpgsqlDbType.Json));
}
else
{
command.Parameters.Add(NpgsqlRestParameter.CreateParamWithType(NpgsqlDbType.Text | NpgsqlDbType.Array));
}
}
if (paramCount >= 3) command.Parameters.Add(new NpgsqlParameter());
if (paramCount >= 4) command.Parameters.Add(NpgsqlRestParameter.CreateParamWithType(NpgsqlDbType.Json));
// Build user claims JSON once (reused for all rows)
string? userClaimsJson = null;
var claimsKey = options.DefaultUploadHandlerOptions.RowCommandUserClaimsKey;
if (string.IsNullOrEmpty(claimsKey) is false && context.User?.Identity?.IsAuthenticated == true)
{
userClaimsJson = $",{PgConverters.SerializeString(claimsKey)}:{context.User.BuildClaimsDictionary(Options.AuthenticationOptions).GetUserClaimsDbParam()}";
}
StringBuilder result = new(context.Request.Form.Files.Count * 100);
result.Append('[');
int fileId = 0;
for (int i = 0; i < context.Request.Form.Files.Count; i++)
{
IFormFile formFile = context.Request.Form.Files[i];
StringBuilder fileJson = new(100);
if (Type is not null)
{
fileJson.Append("{\"type\":");
fileJson.Append(PgConverters.SerializeString(Type));
fileJson.Append(",\"fileName\":");
}
else
{
fileJson.Append("{\"fileName\":");
}
fileJson.Append(PgConverters.SerializeString(formFile.FileName));
fileJson.Append(",\"contentType\":");
fileJson.Append(PgConverters.SerializeString(formFile.ContentType));
fileJson.Append(",\"size\":");
fileJson.Append(formFile.Length);
UploadFileStatus status = UploadFileStatus.Ok;
if (StopAfterFirstSuccess is true && SkipFileNames.Contains(formFile.FileName, StringComparer.OrdinalIgnoreCase))
{
status = UploadFileStatus.Ignored;
}
if (status == UploadFileStatus.Ok && this.CheckMimeTypes(formFile.ContentType) is false)
{
status = UploadFileStatus.InvalidMimeType;
}
if (status != UploadFileStatus.Ok)
{
fileJson.Append(",\"success\":false,\"status\":");
fileJson.Append(PgConverters.SerializeString(status.ToString()));
fileJson.Append('}');
Logger?.FileUploadFailed(Type, formFile.FileName, formFile.ContentType, formFile.Length, status);
result.Append(fileJson);
if (i < context.Request.Form.Files.Count - 1) result.Append(',');
continue;
}
if (StopAfterFirstSuccess is true)
{
SkipFileNames.Add(formFile.FileName);
}
try
{
using var stream = formFile.OpenReadStream();
using IExcelDataReader reader = ExcelReaderFactory.CreateReader(stream);
do
{
string sheetName = reader.Name;
if (allSheets is false &&
string.IsNullOrEmpty(targetSheetName) is false &&
string.Equals(sheetName, targetSheetName, StringComparison.OrdinalIgnoreCase) is false)
{
continue; // Skip this sheet
}
if (fileId > 0)
{
result.Append(',');
}
var rowMeta = string.Concat(fileJson.ToString(),
",\"sheet\":",
PgConverters.SerializeDatbaseObject(sheetName),
userClaimsJson ?? "");
object? commandResult = null;
int excelRowIndex = 0, rowIndex = 0;
while (reader.Read())
{
excelRowIndex++;
object? values = dataAsJson is true ? GetJsonFromReader(reader, excelRowIndex) : GetValuesFromReader(reader);
if (values is null)
{
continue;
}
rowIndex++;
if (paramCount >= 1)
{
command.Parameters[0].Value = rowIndex;
}
if (paramCount >= 2)
{
command.Parameters[1].Value = values ?? DBNull.Value;
}
if (paramCount >= 3)
{
command.Parameters[2].Value = commandResult ?? DBNull.Value;
}
if (paramCount >= 4)
{
command.Parameters[3].Value = string.Concat(rowMeta, ",\"rowIndex\":", excelRowIndex, '}');
}
commandResult = await command.ExecuteScalarWithRetryAsync(cmdRetryStrategy, cancellationToken);
}
var finalJson = string.Concat(rowMeta,
",\"success\":true,\"rows\":",
rowIndex - 1,
",\"result\":",
PgConverters.SerializeDatbaseObject(commandResult),
'}');
result.Append(finalJson);
fileId++;
if (allSheets is false &&
string.IsNullOrEmpty(targetSheetName) is true)
{
break; // Only process the first sheet if not all sheets are requested
}
} while (reader.NextResult());
}
catch (Exception ex)
{
var fallbackResult = await RunFallbackAsync(cmdRetryStrategy, connection, context, options, parameters, cancellationToken);
if (fallbackResult is not null)
{
return fallbackResult;
}
Logger?.LogError(ex, "Error processing Excel file {fileName}", formFile.FileName);
if (fileId > 0)
{
result.Append(',');
}
fileJson.Append(",\"success\":false,\"status\":");
fileJson.Append(PgConverters.SerializeString(UploadFileStatus.InvalidFormat.ToString()));
fileJson.Append('}');
result.Append(fileJson);
fileId++;
}
}
result.Append(']');
return result.ToString();
}
public void OnError(NpgsqlConnection? connection, HttpContext context, Exception? exception)
{
}
private string GetJsonFromReader(IExcelDataReader reader, int rowIndex)
{
StringBuilder sb = new(100);
sb.Append('{');
bool first = true;
for (int i = 0; i < reader.FieldCount; i++)
{
if (reader.IsDBNull(i))
{
continue; // Skip null values
}
if (first)
{
first = false;
}
else
{
sb.Append(',');
}
sb.Append('"');
sb.Append(GetColumnLetter(i));
sb.Append(rowIndex);
sb.Append('"');
sb.Append(':');
sb.Append(PgConverters.SerializeDatbaseObject(GetValueFromReader(reader, i)));
}
if (first)
{
return null!;
}
sb.Append('}');
return sb.ToString();
}
private string?[]? GetValuesFromReader(IExcelDataReader reader)
{
var values = new string?[reader.FieldCount];
int nullCount = 0;
for (int i = 0; i < reader.FieldCount; i++)
{
if (reader.IsDBNull(i))
{
values[i] = null;
nullCount++;
}
else
{
values[i] = GetValueFromReader(reader, i);
}
}
return nullCount == reader.FieldCount ? null : values;
}
private string? GetValueFromReader(IExcelDataReader reader, int i)
{
if (reader.GetFieldType(i) == typeof(DateTime))
{
var date = reader.GetDateTime(i);
if (date.TimeOfDay == TimeSpan.Zero)
{
return date.ToString(_dateFormat);
}
if (date.Year == 1899 && date.Month == 12 && date.Day == 31)
{
return date.ToString(_timeFormat);
}
return date.ToString(_dateTimeFormat);
}
return reader.GetValue(i)?.ToString();
}
private static string GetColumnLetter(int columnIndex)
{
string columnName = "";
while (columnIndex >= 0)
{
columnName = (char)('A' + columnIndex % 26) + columnName;
columnIndex = columnIndex / 26 - 1;
}
return columnName;
}
}