-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathDbDriver.cs
More file actions
368 lines (314 loc) · 13.6 KB
/
Copy pathDbDriver.cs
File metadata and controls
368 lines (314 loc) · 13.6 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
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Plugin;
using System;
using System.Collections.Generic;
using System.Linq;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace SqlcGenCsharp.Drivers;
public record ConnectionGenCommands(string EstablishConnection, string ConnectionOpen);
public abstract class DbDriver
{
public Options Options { get; }
public string DefaultSchema { get; }
public abstract string TransactionClassName { get; }
public Dictionary<string, Dictionary<string, Table>> Tables { get; }
protected IList<Query> Queries { get; }
private HashSet<string> NullableTypesInDotnetCore { get; } =
[
"string",
"object",
"PhysicalAddress",
"IPAddress"
];
protected HashSet<string> NullableTypes { get; } =
[
"bool",
"byte",
"short",
"int",
"long",
"float",
"double",
"decimal",
"DateTime",
"TimeSpan",
"Guid",
"NpgsqlPoint",
"NpgsqlLine",
"NpgsqlLSeg",
"NpgsqlBox",
"NpgsqlPath",
"NpgsqlPolygon",
"NpgsqlCircle",
"JsonElement",
"NpgsqlCidr",
];
protected abstract Dictionary<string, ColumnMapping> ColumnMappings { get; }
protected const string TransformQueryForSliceArgsImpl = """
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));
}
""";
public readonly string TransactionConnectionNullExcetionThrow = $"""
if (this.{Variable.Transaction.AsPropertyName()}?.Connection == null || this.{Variable.Transaction.AsPropertyName()}?.Connection.State != System.Data.ConnectionState.Open)
throw new InvalidOperationException("Transaction is provided, but its connection is null.");
""";
protected DbDriver(
Options options,
Catalog catalog,
IList<Query> queries)
{
Options = options;
DefaultSchema = catalog.DefaultSchema;
Tables = ConstructTablesLookup(catalog);
Queries = queries;
if (!Options.DotnetFramework.IsDotnetCore())
return;
foreach (var t in NullableTypesInDotnetCore)
NullableTypes.Add(t);
}
private static readonly HashSet<string> _excludedSchemas =
[
"pg_catalog",
"information_schema"
];
private static Dictionary<string, Dictionary<string, Table>> ConstructTablesLookup(Catalog catalog)
{
return catalog.Schemas
.Where(s => !_excludedSchemas.Contains(s.Name))
.ToDictionary(
s => s.Name == catalog.DefaultSchema ? string.Empty : s.Name,
s => s.Tables.ToDictionary(t => t.Rel.Name, t => t)
);
}
public virtual ISet<string> GetUsingDirectivesForQueries()
{
return new HashSet<string>
{
"System",
"System.Collections.Generic",
"System.Threading.Tasks"
}
.AddRangeIf([
"Dapper"
], Options.UseDapper)
.AddRangeExcludeNulls(GetUsingDirectivesForColumnMappings());
}
private ISet<string> GetUsingDirectivesForColumnMappings()
{
var usingDirectives = new HashSet<string>();
foreach (var schemaTables in Tables.Values)
foreach (var table in schemaTables.Values)
foreach (var column in table.Columns)
{
var csharpType = GetCsharpTypeWithoutNullableSuffix(column, null);
if (!ColumnMappings.ContainsKey(csharpType))
continue;
var columnMapping = ColumnMappings[csharpType];
usingDirectives.AddRangeExcludeNulls([columnMapping.UsingDirective]);
}
return usingDirectives;
}
public virtual ISet<string> GetUsingDirectivesForUtils()
{
return new HashSet<string>
{
"System.Linq"
}
.AddRangeIf(["System.Data", "Dapper"], Options.UseDapper)
.AddRangeIf(GetUsingDirectivesForColumnMappings(), Options.UseDapper);
}
public virtual ISet<string> GetUsingDirectivesForModels()
{
return new HashSet<string>
{
"System.Linq"
}
.AddRangeExcludeNulls(GetUsingDirectivesForColumnMappings());
}
public string[] GetConstructorStatements()
{
return [$"this.{Variable.ConnectionString.AsPropertyName()} = {Variable.ConnectionString.AsVarName()};"];
}
public string[] GetTransactionConstructorStatements()
{
return [$"this.{Variable.Transaction.AsPropertyName()} = {Variable.Transaction.AsVarName()};"];
}
protected virtual ISet<string> GetConfigureSqlMappings()
{
return ColumnMappings
.Where(m => TypeExistsInQueries(m.Key) && m.Value.SqlMapper is not null)
.Select(m => m.Value.SqlMapper!)
.ToHashSet();
}
public virtual MemberDeclarationSyntax[] GetMemberDeclarationsForUtils()
{
if (!Options.UseDapper)
return [];
return [..
GetSqlMapperMemberDeclarations(),
ParseMemberDeclaration($$"""
public static void ConfigureSqlMapper()
{
{{GetConfigureSqlMappings().JoinByNewLine()}}
}
""")!];
}
private MemberDeclarationSyntax[] GetSqlMapperMemberDeclarations()
{
return [.. ColumnMappings
.Where(m => TypeExistsInQueries(m.Key) && m.Value.SqlMapperImpl is not null)
.Select(m => ParseMemberDeclaration(m.Value.SqlMapperImpl!(Options.DotnetFramework.IsDotnetCore()))!)];
}
public abstract string TransformQueryText(Query query);
public abstract ConnectionGenCommands EstablishConnection(Query query);
public abstract string CreateSqlCommand(string sqlTextConstant);
/* Since there is no indication of the primary key column in SQLC protobuf (assuming it is a single column),
this method uses a few heuristics to assess the data type of the id column
*/
public string GetIdColumnType(Query query)
{
var tableColumns = Tables[query.InsertIntoTable.Schema][query.InsertIntoTable.Name].Columns;
var idColumn = tableColumns.First(c => c.Name.Equals("id", StringComparison.OrdinalIgnoreCase));
if (idColumn is not null)
return GetCsharpType(idColumn, query);
idColumn = tableColumns.First(c => c.Name.Contains("id", StringComparison.CurrentCultureIgnoreCase));
return GetCsharpType(idColumn ?? tableColumns[0], query);
}
public virtual string[] GetLastIdStatement(Query query)
{
var idColumnType = GetIdColumnType(query);
var convertFunc = ColumnMappings[idColumnType].ConvertFunc ??
throw new InvalidOperationException($"ConvertFunc is missing for id column type {idColumnType}");
var convertFuncCall = convertFunc(Variable.Result.AsVarName());
return
[
$"var {Variable.Result.AsVarName()} = await {Variable.Command.AsVarName()}.ExecuteScalarAsync();",
$"return {convertFuncCall};"
];
}
public Column GetColumnFromParam(Parameter queryParam, Query query)
{
if (string.IsNullOrEmpty(queryParam.Column.Name))
queryParam.Column.Name = $"{GetCsharpType(queryParam.Column, query).Replace("[]", "Arr")}_{queryParam.Number}";
return queryParam.Column;
}
protected bool TypeExistsInQueries(string csharpType)
{
return Queries.Any(q => TypeExistsInQuery(csharpType, q));
}
protected bool TypeExistsInQuery(string csharpType, Query query)
{
return query.Columns
.Any(column => csharpType == GetCsharpTypeWithoutNullableSuffix(column, query)) ||
query.Params
.Any(p => csharpType == GetCsharpTypeWithoutNullableSuffix(p.Column, query));
}
protected bool SliceQueryExists()
{
return Queries.Any(q => q.Params.Any(p => p.Column.IsSqlcSlice));
}
protected bool CopyFromQueryExists()
{
return Queries.Any(q => q.Cmd is ":copyfrom");
}
private OverrideOption? FindOverrideForQueryColumn(Query? query, Column column)
{
if (query is null)
return null;
foreach (var overrideOption in Options.Overrides)
if (overrideOption.Column == $"{query.Name}:{column.Name}" || overrideOption.Column == $"*:{column.Name}")
return overrideOption;
return null;
}
// If the column data type is overridden, we need to check for nulls in generated code
public bool IsColumnNotNull(Column column, Query? query)
{
if (FindOverrideForQueryColumn(query, column) is { CsharpType: var csharpType })
return csharpType.NotNull;
return column.NotNull;
}
/* Data type methods */
public string GetCsharpType(Column column, Query? query)
{
var csharpType = GetCsharpTypeWithoutNullableSuffix(column, query);
return AddNullableSuffixIfNeeded(csharpType, IsColumnNotNull(column, query));
}
public string AddNullableSuffixIfNeeded(string csharpType, bool notNull)
{
if (notNull)
return csharpType;
return IsTypeNullable(csharpType) ? $"{csharpType}?" : csharpType;
}
protected string? GetColumnDbTypeOverride(Column column)
{
var columnType = column.Type.Name.ToLower();
foreach (var columnMapping in ColumnMappings.Values)
{
if (columnMapping.DbTypes.TryGetValue(columnType, out var dbTypeOverride))
return dbTypeOverride.NpgsqlTypeOverride;
}
throw new NotSupportedException($"Column {column.Name} has unsupported column type: {column.Type.Name}");
}
public bool IsTypeNullable(string csharpType)
{
if (NullableTypes.Contains(csharpType.Replace("?", ""))) return true;
return Options.DotnetFramework.IsDotnetCore(); // non-primitives in .Net Core are inherently nullable
}
protected virtual string GetCsharpTypeWithoutNullableSuffix(Column column, Query? query)
{
if (column.EmbedTable != null)
return column.EmbedTable.Name.ToModelName(column.EmbedTable.Schema, DefaultSchema);
if (string.IsNullOrEmpty(column.Type.Name))
return "object";
if (FindOverrideForQueryColumn(query, column) is { CsharpType: var csharpType })
return csharpType.Type;
foreach (var columnMapping in ColumnMappings
.Where(columnMapping => DoesColumnMappingApply(columnMapping.Value, column)))
{
if (column.IsArray || column.IsSqlcSlice) return $"{columnMapping.Key}[]";
return columnMapping.Key;
}
throw new NotSupportedException($"Column {column.Name} has unsupported column type: {column.Type.Name} in {GetType().Name}");
}
private static bool DoesColumnMappingApply(ColumnMapping columnMapping, Column column)
{
var columnType = column.Type.Name.ToLower();
if (!columnMapping.DbTypes.TryGetValue(columnType, out var typeInfo))
return false;
if (typeInfo.Length is null)
return true;
return typeInfo.Length.Value == column.Length;
}
public virtual WriterFn? GetWriterFn(Column column, Query query)
{
var csharpType = GetCsharpTypeWithoutNullableSuffix(column, query);
var writerFn = ColumnMappings.GetValueOrDefault(csharpType)?.WriterFn;
if (writerFn is not null)
return writerFn;
static string DefaultWriterFn(string el, string dbType, bool notNull, bool isDapper, bool isLegacy) => notNull ? el : $"{el} ?? (object)DBNull.Value";
return Options.UseDapper ? null : DefaultWriterFn;
}
/* Column reader methods */
private string GetColumnReader(CsharpTypeOption csharpTypeOption, Column column, int ordinal)
{
if (ColumnMappings.TryGetValue(csharpTypeOption.Type, out var value))
return value.ReaderFn(ordinal, column.Type.Name);
throw new NotSupportedException($"Could not find column mapping for type override: {csharpTypeOption.Type}");
}
public virtual string GetColumnReader(Column column, int ordinal, Query? query)
{
if (FindOverrideForQueryColumn(query, column) is { CsharpType: var csharpType })
return GetColumnReader(csharpType, column, ordinal);
foreach (var columnMapping in ColumnMappings.Values
.Where(columnMapping => DoesColumnMappingApply(columnMapping, column)))
{
if (column.IsArray)
return columnMapping.ReaderArrayFn?.Invoke(ordinal, column.Type.Name) ?? throw new InvalidOperationException("ReaderArrayFn is null");
return columnMapping.ReaderFn(ordinal, column.Type.Name);
}
throw new NotSupportedException($"column {column.Name} has unsupported column type: {column.Type.Name} in {GetType().Name}");
}
}