-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathUtils.cs
More file actions
73 lines (66 loc) · 3.02 KB
/
Utils.cs
File metadata and controls
73 lines (66 loc) · 3.02 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
// auto-generated by sqlc - do not edit
namespace SqliteDapperLegacyExampleGen
{
using Dapper;
using NodaTime;
using NodaTime.Extensions;
using NodaTime.Text;
using System;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
public static class Utils
{
private class DateTimeTypeHandler : SqlMapper.TypeHandler<DateTime>
{
public override DateTime Parse(object value)
{
if (value is string s)
return DateTime.Parse(s);
if (value is long l)
return DateTimeOffset.FromUnixTimeSeconds(l).DateTime;
throw new DataException($"Cannot convert {value?.GetType()} to DateTime");
}
public override void SetValue(IDbDataParameter parameter, DateTime value)
{
parameter.Value = value;
}
}
private class NodaInstantTypeHandler : SqlMapper.TypeHandler<Instant>
{
public override Instant Parse(object value)
{
if (value is string s)
return InstantPattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss").Parse(s).Value;
if (value is long l)
return Instant.FromUnixTimeSeconds(l);
throw new DataException($"Cannot convert {value?.GetType()} to Instant");
}
public override void SetValue(IDbDataParameter parameter, Instant value)
{
parameter.Value = value;
}
}
public static void ConfigureSqlMapper()
{
SqlMapper.AddTypeHandler(typeof(DateTime), new DateTimeTypeHandler());
SqlMapper.AddTypeHandler(typeof(Instant), new NodaInstantTypeHandler());
}
public static string TransformQueryForSliceArgs(string originalSql, int sliceSize, string paramName)
{
var paramArgs = Enumerable.Range(0, sliceSize).Select(i => $"@{paramName}Arg{i}").ToList();
return originalSql.Replace($"/*SLICE:{paramName}*/@{paramName}", string.Join(",", paramArgs));
}
private static readonly Regex ValuesRegex = new Regex(@"VALUES\s*\((?<params>[^)]*)\)", RegexOptions.IgnoreCase);
public static string TransformQueryForSqliteBatch(string originalSql, int cntRecords)
{
var match = ValuesRegex.Match(originalSql);
if (!match.Success)
throw new ArgumentException("The query does not contain a valid VALUES clause.");
var valuesParams = match.Groups["params"].Value.Split(',').Select(p => p.Trim()).ToList();
var batchRows = Enumerable.Range(0, cntRecords).Select(i => "(" + string.Join(", ", valuesParams.Select(p => $"{p}{i}")) + ")");
var batchValuesClause = "VALUES " + string.Join(",\n", batchRows);
return ValuesRegex.Replace(originalSql, batchValuesClause);
}
}
}