-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDbSet.cs
More file actions
1123 lines (913 loc) · 40.2 KB
/
DbSet.cs
File metadata and controls
1123 lines (913 loc) · 40.2 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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Data;
using System.Collections.Concurrent;
using System.Collections;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Text.Json;
using Dapper;
namespace CodeWorks.SimpleSql;
public interface ISqlSession
{
IDbSet<T> Set<T>();
}
public interface IDbSet<T>
{
IDbSet<T> Where(Expression<Func<T, bool>> predicate);
IDbSet<T> Search(string keyword, SqlSearchOptions? options = null, Dictionary<string, string>? filters = null);
IDbSet<T> Include<TJoin>(Expression<Func<T, object?>> navigation, SqlJoinType joinType = SqlJoinType.Left, string? alias = null);
IDbSet<T> OrderBy(Expression<Func<T, object>> expression, bool desc = false);
IDbSet<T> Page(int page, int size);
IProjectedDbSet<TProjection> Select<TProjection>();
Task<List<T>> ToListAsync(IDbTransaction? transaction = null, CancellationToken cancellationToken = default);
Task<T?> FirstOrDefaultAsync(IDbTransaction? transaction = null, CancellationToken cancellationToken = default);
Task<int> CountAsync(IDbTransaction? transaction = null, CancellationToken cancellationToken = default);
Task<bool> AnyAsync(IDbTransaction? transaction = null, CancellationToken cancellationToken = default);
Task<int> UpsertAsync(T entity, Expression<Func<T, object>> keySelector, IDbTransaction? transaction = null, CancellationToken cancellationToken = default);
Task<int> UpsertManyAsync(IEnumerable<T> entities, Expression<Func<T, object>> keySelector, int batchSize = 200, IDbTransaction? transaction = null, CancellationToken cancellationToken = default);
CompiledQuery ToUpsertCompiledQuery(T entity, Expression<Func<T, object>> keySelector);
CompiledQuery ToCompiledQuery();
CompiledQuery ToCompiledQuery(SqlQueryResultMode mode);
}
public interface IProjectedDbSet<TProjection>
{
Task<List<TProjection>> ToListAsync(IDbTransaction? transaction = null, CancellationToken cancellationToken = default);
Task<TProjection?> FirstOrDefaultAsync(IDbTransaction? transaction = null, CancellationToken cancellationToken = default);
CompiledQuery ToCompiledQuery();
CompiledQuery ToCompiledQuery(SqlQueryResultMode mode);
}
public sealed class SqlSession : ISqlSession
{
private readonly IDbConnection _db;
private readonly ISqlDialect _dialect;
public SqlSession(IDbConnection db, ISqlDialect? dialect = null)
{
_db = db;
_dialect = dialect ?? SqlDialects.Detect(db);
}
public IDbSet<T> Set<T>() => new DbSet<T>(_db, _dialect);
}
public sealed class DbSet<T> : IDbSet<T>
{
private readonly IDbConnection _db;
private readonly ISqlDialect _dialect;
private readonly SqlQueryModel _model;
public DbSet(IDbConnection db, ISqlDialect? dialect = null)
{
_db = db;
_dialect = dialect ?? SqlDialects.Detect(db);
_model = SqlQueryModel.Create(typeof(T));
}
private DbSet(IDbConnection db, ISqlDialect dialect, SqlQueryModel model)
{
_db = db;
_dialect = dialect;
_model = model;
}
public IDbSet<T> Where(Expression<Func<T, bool>> predicate)
=> new DbSet<T>(_db, _dialect, _model.AddWhere(predicate));
public IDbSet<T> Search(string keyword, SqlSearchOptions? options = null, Dictionary<string, string>? filters = null)
=> new DbSet<T>(_db, _dialect, _model.SetSearch(keyword, options, filters));
public IDbSet<T> Include<TJoin>(
Expression<Func<T, object?>> navigation,
SqlJoinType joinType = SqlJoinType.Left,
string? alias = null)
=> new DbSet<T>(_db, _dialect, _model.AddInclude(typeof(TJoin), navigation, joinType, alias));
public IDbSet<T> OrderBy(Expression<Func<T, object>> expression, bool desc = false)
=> new DbSet<T>(_db, _dialect, _model.AddOrder(expression, desc));
public IDbSet<T> Page(int page, int size)
{
if (page < 1) throw new ArgumentOutOfRangeException(nameof(page));
if (size < 1) throw new ArgumentOutOfRangeException(nameof(size));
return new DbSet<T>(_db, _dialect, _model.SetPaging(page, size));
}
public IProjectedDbSet<TProjection> Select<TProjection>() =>
new ProjectedDbSet<T, TProjection>(_db, _dialect, _model);
public CompiledQuery ToCompiledQuery() => ToCompiledQuery(SqlQueryResultMode.List);
public CompiledQuery ToCompiledQuery(SqlQueryResultMode mode) => SqlQueryCompiler.Compile(_model, _dialect, mode);
public async Task<List<T>> ToListAsync(
IDbTransaction? transaction = null,
CancellationToken cancellationToken = default)
{
EnsureTransactionConnectionMatches(transaction);
if (_model.Includes.Count > 0)
return await ToListWithIncludesAsync(transaction, cancellationToken);
var compiled = ToCompiledQuery();
var command = new CommandDefinition(
compiled.Sql,
compiled.Parameters,
transaction: transaction,
cancellationToken: cancellationToken);
var rows = await _db.QueryAsync<T>(command);
return rows.ToList();
}
public async Task<T?> FirstOrDefaultAsync(
IDbTransaction? transaction = null,
CancellationToken cancellationToken = default)
{
EnsureTransactionConnectionMatches(transaction);
if (_model.Includes.Count > 0)
return await FirstOrDefaultWithIncludesAsync(transaction, cancellationToken);
var compiled = ToCompiledQuery(SqlQueryResultMode.First);
var command = new CommandDefinition(
compiled.Sql,
compiled.Parameters,
transaction: transaction,
cancellationToken: cancellationToken);
return await _db.QueryFirstOrDefaultAsync<T>(command);
}
public async Task<int> CountAsync(
IDbTransaction? transaction = null,
CancellationToken cancellationToken = default)
{
EnsureTransactionConnectionMatches(transaction);
var compiled = ToCompiledQuery(SqlQueryResultMode.Count);
var command = new CommandDefinition(
compiled.Sql,
compiled.Parameters,
transaction: transaction,
cancellationToken: cancellationToken);
return await _db.ExecuteScalarAsync<int>(command);
}
public async Task<bool> AnyAsync(
IDbTransaction? transaction = null,
CancellationToken cancellationToken = default)
{
EnsureTransactionConnectionMatches(transaction);
var compiled = ToCompiledQuery(SqlQueryResultMode.Exists);
var command = new CommandDefinition(
compiled.Sql,
compiled.Parameters,
transaction: transaction,
cancellationToken: cancellationToken);
return await _db.ExecuteScalarAsync<bool>(command);
}
public CompiledQuery ToUpsertCompiledQuery(T entity, Expression<Func<T, object>> keySelector)
=> SqlWriteCompiler.BuildUpsert(entity, keySelector, _dialect);
public async Task<int> UpsertAsync(
T entity,
Expression<Func<T, object>> keySelector,
IDbTransaction? transaction = null,
CancellationToken cancellationToken = default)
{
EnsureTransactionConnectionMatches(transaction);
var compiled = ToUpsertCompiledQuery(entity, keySelector);
var command = new CommandDefinition(
compiled.Sql,
compiled.Parameters,
transaction: transaction,
cancellationToken: cancellationToken);
return await _db.ExecuteAsync(command);
}
public async Task<int> UpsertManyAsync(
IEnumerable<T> entities,
Expression<Func<T, object>> keySelector,
int batchSize = 200,
IDbTransaction? transaction = null,
CancellationToken cancellationToken = default)
{
EnsureTransactionConnectionMatches(transaction);
ArgumentNullException.ThrowIfNull(entities);
if (batchSize < 1)
throw new ArgumentOutOfRangeException(nameof(batchSize));
var rows = entities as IList<T> ?? entities.ToList();
if (rows.Count == 0)
return 0;
var plan = SqlWriteCompiler.BuildUpsertPlan(keySelector, _dialect);
var total = 0;
foreach (var batch in rows.Chunk(batchSize))
{
var parameterBatch = batch
.Select(row => (object)SqlWriteCompiler.BuildUpsertParameters(row, plan.InsertProps))
.ToList();
var command = new CommandDefinition(
plan.Sql,
parameterBatch,
transaction: transaction,
cancellationToken: cancellationToken);
total += await _db.ExecuteAsync(command);
}
return total;
}
private void EnsureTransactionConnectionMatches(IDbTransaction? transaction)
{
if (transaction?.Connection != null && !ReferenceEquals(transaction.Connection, _db))
throw new InvalidOperationException("The provided transaction does not belong to the DbSet connection.");
}
private async Task<List<T>> ToListWithIncludesAsync(
IDbTransaction? transaction,
CancellationToken cancellationToken)
{
var compiled = SqlQueryCompiler.CompileNested(_model, _dialect, SqlQueryResultMode.List);
var command = new CommandDefinition(
compiled.Sql,
compiled.Parameters,
transaction: transaction,
cancellationToken: cancellationToken);
var rows = await _db.QueryAsync(command);
return rows
.Cast<object>()
.Select(row => SqlQueryCompiler.MapNestedRow<T>(row, compiled))
.ToList();
}
private async Task<T?> FirstOrDefaultWithIncludesAsync(
IDbTransaction? transaction,
CancellationToken cancellationToken)
{
var compiled = SqlQueryCompiler.CompileNested(_model, _dialect, SqlQueryResultMode.First);
var command = new CommandDefinition(
compiled.Sql,
compiled.Parameters,
transaction: transaction,
cancellationToken: cancellationToken);
var row = await _db.QueryFirstOrDefaultAsync(command);
return row == null ? default : SqlQueryCompiler.MapNestedRow<T>(row, compiled);
}
}
public sealed class ProjectedDbSet<TRoot, TProjection> : IProjectedDbSet<TProjection>
{
private readonly IDbConnection _db;
private readonly ISqlDialect _dialect;
private readonly SqlQueryModel _model;
internal ProjectedDbSet(IDbConnection db, ISqlDialect dialect, SqlQueryModel model)
{
_db = db;
_dialect = dialect;
_model = model;
}
public CompiledQuery ToCompiledQuery() => ToCompiledQuery(SqlQueryResultMode.List);
public CompiledQuery ToCompiledQuery(SqlQueryResultMode mode) =>
SqlQueryCompiler.CompileProjected<TRoot, TProjection>(_model, _dialect, mode);
public async Task<List<TProjection>> ToListAsync(
IDbTransaction? transaction = null,
CancellationToken cancellationToken = default)
{
EnsureTransactionConnectionMatches(transaction);
var compiled = ToCompiledQuery(SqlQueryResultMode.List);
var command = new CommandDefinition(
compiled.Sql,
compiled.Parameters,
transaction: transaction,
cancellationToken: cancellationToken);
var rows = await _db.QueryAsync<TProjection>(command);
return rows.ToList();
}
public async Task<TProjection?> FirstOrDefaultAsync(
IDbTransaction? transaction = null,
CancellationToken cancellationToken = default)
{
EnsureTransactionConnectionMatches(transaction);
var compiled = ToCompiledQuery(SqlQueryResultMode.First);
var command = new CommandDefinition(
compiled.Sql,
compiled.Parameters,
transaction: transaction,
cancellationToken: cancellationToken);
return await _db.QueryFirstOrDefaultAsync<TProjection>(command);
}
private void EnsureTransactionConnectionMatches(IDbTransaction? transaction)
{
if (transaction?.Connection != null && !ReferenceEquals(transaction.Connection, _db))
throw new InvalidOperationException("The provided transaction does not belong to the DbSet connection.");
}
}
public readonly record struct CompiledQuery(string Sql, DynamicParameters Parameters);
internal readonly record struct NestedIncludePlan(string Alias, PropertyInfo NavigationProperty, SqlEntityMap Map);
internal readonly record struct NestedCompiledQuery(
string Sql,
DynamicParameters Parameters,
SqlEntityMap RootMap,
IReadOnlyList<NestedIncludePlan> Includes);
public enum SqlQueryResultMode
{
List,
First,
Count,
Exists
}
internal readonly record struct IncludeSpec(
Type JoinType,
LambdaExpression Navigation,
SqlJoinType JoinKind,
string? Alias);
internal readonly record struct OrderSpec(LambdaExpression Expression, bool Desc);
internal sealed class SqlQueryModel
{
public Type RootType { get; }
public IReadOnlyList<LambdaExpression> Wheres { get; }
public string? SearchKeyword { get; }
public SqlSearchOptions? SearchOptions { get; }
public IReadOnlyDictionary<string, string>? SearchFilters { get; }
public IReadOnlyList<IncludeSpec> Includes { get; }
public IReadOnlyList<OrderSpec> Orders { get; }
public int? Limit { get; }
public int? Offset { get; }
private SqlQueryModel(
Type rootType,
IReadOnlyList<LambdaExpression>? wheres = null,
string? searchKeyword = null,
SqlSearchOptions? searchOptions = null,
IReadOnlyDictionary<string, string>? searchFilters = null,
IReadOnlyList<IncludeSpec>? includes = null,
IReadOnlyList<OrderSpec>? orders = null,
int? limit = null,
int? offset = null)
{
RootType = rootType;
Wheres = wheres ?? [];
SearchKeyword = searchKeyword;
SearchOptions = searchOptions;
SearchFilters = searchFilters;
Includes = includes ?? [];
Orders = orders ?? [];
Limit = limit;
Offset = offset;
}
public static SqlQueryModel Create(Type rootType) => new(rootType);
public SqlQueryModel AddWhere(LambdaExpression expression)
{
var next = Wheres.ToList();
next.Add(expression);
return new SqlQueryModel(RootType, next, SearchKeyword, SearchOptions, SearchFilters, Includes, Orders, Limit, Offset);
}
public SqlQueryModel SetSearch(string keyword, SqlSearchOptions? options, Dictionary<string, string>? filters)
{
ArgumentException.ThrowIfNullOrWhiteSpace(keyword);
var nextFilters = filters == null
? null
: new Dictionary<string, string>(filters, StringComparer.OrdinalIgnoreCase);
return new SqlQueryModel(RootType, Wheres, keyword, options, nextFilters, Includes, Orders, Limit, Offset);
}
public SqlQueryModel AddInclude(Type joinType, LambdaExpression navigation, SqlJoinType joinKind, string? alias)
{
var next = Includes.ToList();
next.Add(new IncludeSpec(joinType, navigation, joinKind, alias));
return new SqlQueryModel(RootType, Wheres, SearchKeyword, SearchOptions, SearchFilters, next, Orders, Limit, Offset);
}
public SqlQueryModel AddOrder(LambdaExpression expression, bool desc)
{
var next = Orders.ToList();
next.Add(new OrderSpec(expression, desc));
return new SqlQueryModel(RootType, Wheres, SearchKeyword, SearchOptions, SearchFilters, Includes, next, Limit, Offset);
}
public SqlQueryModel SetPaging(int page, int size)
{
var offset = (page - 1) * size;
return new SqlQueryModel(RootType, Wheres, SearchKeyword, SearchOptions, SearchFilters, Includes, Orders, size, offset);
}
}
internal static class SqlQueryCompiler
{
private static readonly ConcurrentDictionary<string, string> ProjectionSelectCache = new();
public static CompiledQuery Compile(
SqlQueryModel model,
ISqlDialect dialect,
SqlQueryResultMode mode = SqlQueryResultMode.List)
{
var parameters = new DynamicParameters();
var query = CreateTypedQuery(model.RootType, dialect);
foreach (var include in model.Includes)
query = ApplyInclude(query, include);
var fromSql = (string)(query.GetType()
.GetMethod(nameof(SqlQuery<object>.BuildFrom))
?.Invoke(query, null)
?? throw new InvalidOperationException("Failed to build FROM SQL."));
var selectSql = (string)(query.GetType()
.GetMethod(nameof(SqlQuery<object>.BuildSelect))
?.Invoke(query, null)
?? throw new InvalidOperationException("Failed to build SELECT SQL."));
var whereParts = model.Wheres
.Select(w => SqlExpressionBuilder.Build(w, SQLMapper.Get(model.RootType), parameters, "t0", dialect).Replace("WHERE ", string.Empty))
.Where(w => !string.IsNullOrWhiteSpace(w))
.ToList();
string? searchRankSql = null;
if (!string.IsNullOrWhiteSpace(model.SearchKeyword) || model.SearchFilters?.Count > 0)
{
var (searchWhereSql, rankSql) = SqlHelper.BuildFilter(
model.RootType,
model.SearchKeyword,
model.SearchFilters == null ? null : new Dictionary<string, string>(model.SearchFilters, StringComparer.OrdinalIgnoreCase),
parameters,
dialect,
"t0",
model.SearchOptions);
if (!string.IsNullOrWhiteSpace(searchWhereSql))
whereParts.Add(searchWhereSql.Replace("WHERE ", string.Empty));
searchRankSql = rankSql;
}
var whereSql = whereParts.Count == 0
? string.Empty
: " WHERE " + string.Join(" AND ", whereParts);
var orderParts = model.Orders
.Select(o => SqlHelper.BuildOrderBy(o.Expression, model.RootType, "t0", o.Desc, dialect))
.ToList();
if (!string.IsNullOrWhiteSpace(searchRankSql))
orderParts.Insert(0, $"{searchRankSql} DESC");
var orderSql = orderParts.Count == 0
? string.Empty
: " ORDER BY " + string.Join(", ", orderParts);
var hasPaging = model.Limit.HasValue || model.Offset.HasValue;
var sqlServerPagingNeedsOrderFallback =
hasPaging
&& orderParts.Count == 0
&& string.Equals(dialect.Name, "sqlserver", StringComparison.OrdinalIgnoreCase);
var pagingSql = SqlHelper.BuildPaging(
model.Limit,
model.Offset,
dialect,
forceOrderByForSqlServer: sqlServerPagingNeedsOrderFallback);
var paging = string.IsNullOrWhiteSpace(pagingSql) ? string.Empty : " " + pagingSql;
var baseQuerySql = $"{selectSql} {fromSql}{whereSql}";
var sql = mode switch
{
SqlQueryResultMode.List => $"{baseQuerySql}{orderSql}{paging}",
SqlQueryResultMode.First => BuildFirstSql(baseQuerySql, orderSql, dialect),
SqlQueryResultMode.Count => $"SELECT COUNT(1) {fromSql}{whereSql}",
SqlQueryResultMode.Exists => BuildExistsSql(fromSql, whereSql, dialect),
_ => throw new NotSupportedException($"Unsupported query mode: {mode}")
};
return new CompiledQuery(sql, parameters);
}
public static CompiledQuery CompileProjected<TRoot, TProjection>(
SqlQueryModel model,
ISqlDialect dialect,
SqlQueryResultMode mode = SqlQueryResultMode.List)
{
if (model.RootType != typeof(TRoot))
throw new InvalidOperationException("Projection root type mismatch.");
if (mode is not (SqlQueryResultMode.List or SqlQueryResultMode.First))
throw new NotSupportedException("Projected queries currently support only List and First modes.");
var parameters = new DynamicParameters();
var query = CreateTypedQuery(model.RootType, dialect);
foreach (var include in model.Includes)
query = ApplyInclude(query, include);
var fromSql = (string)(query.GetType()
.GetMethod(nameof(SqlQuery<object>.BuildFrom))
?.Invoke(query, null)
?? throw new InvalidOperationException("Failed to build projected FROM SQL."));
var whereParts = model.Wheres
.Select(w => SqlExpressionBuilder.Build(w, SQLMapper.Get(model.RootType), parameters, "t0", dialect).Replace("WHERE ", string.Empty))
.Where(w => !string.IsNullOrWhiteSpace(w))
.ToList();
string? searchRankSql = null;
if (!string.IsNullOrWhiteSpace(model.SearchKeyword) || model.SearchFilters?.Count > 0)
{
var (searchWhereSql, rankSql) = SqlHelper.BuildFilter(
model.RootType,
model.SearchKeyword,
model.SearchFilters == null ? null : new Dictionary<string, string>(model.SearchFilters, StringComparer.OrdinalIgnoreCase),
parameters,
dialect,
"t0",
model.SearchOptions);
if (!string.IsNullOrWhiteSpace(searchWhereSql))
whereParts.Add(searchWhereSql.Replace("WHERE ", string.Empty));
searchRankSql = rankSql;
}
var whereSql = whereParts.Count == 0
? string.Empty
: " WHERE " + string.Join(" AND ", whereParts);
var orderParts = model.Orders
.Select(o => SqlHelper.BuildOrderBy(o.Expression, model.RootType, "t0", o.Desc, dialect))
.ToList();
if (!string.IsNullOrWhiteSpace(searchRankSql))
orderParts.Insert(0, $"{searchRankSql} DESC");
var orderSql = orderParts.Count == 0
? string.Empty
: " ORDER BY " + string.Join(", ", orderParts);
var hasPaging = model.Limit.HasValue || model.Offset.HasValue;
var sqlServerPagingNeedsOrderFallback =
hasPaging
&& orderParts.Count == 0
&& string.Equals(dialect.Name, "sqlserver", StringComparison.OrdinalIgnoreCase);
var pagingSql = SqlHelper.BuildPaging(
model.Limit,
model.Offset,
dialect,
forceOrderByForSqlServer: sqlServerPagingNeedsOrderFallback);
var paging = string.IsNullOrWhiteSpace(pagingSql) ? string.Empty : " " + pagingSql;
var selectSql = BuildProjectionSelectSql(model.RootType, model.Includes, typeof(TProjection), dialect, "t0");
var baseQuerySql = $"{selectSql} {fromSql}{whereSql}";
var sql = mode switch
{
SqlQueryResultMode.List => $"{baseQuerySql}{orderSql}{paging}",
SqlQueryResultMode.First => BuildFirstSql(baseQuerySql, orderSql, dialect),
_ => throw new NotSupportedException("Unsupported projection query mode")
};
return new CompiledQuery(sql, parameters);
}
public static NestedCompiledQuery CompileNested(
SqlQueryModel model,
ISqlDialect dialect,
SqlQueryResultMode mode)
{
if (mode is not (SqlQueryResultMode.List or SqlQueryResultMode.First))
throw new NotSupportedException("Nested query compilation supports List and First modes only.");
var parameters = new DynamicParameters();
var query = CreateTypedQuery(model.RootType, dialect);
foreach (var include in model.Includes)
query = ApplyInclude(query, include);
var fromSql = (string)(query.GetType()
.GetMethod(nameof(SqlQuery<object>.BuildFrom))
?.Invoke(query, null)
?? throw new InvalidOperationException("Failed to build nested FROM SQL."));
var whereParts = model.Wheres
.Select(w => SqlExpressionBuilder.Build(w, SQLMapper.Get(model.RootType), parameters, "t0", dialect).Replace("WHERE ", string.Empty))
.Where(w => !string.IsNullOrWhiteSpace(w))
.ToList();
string? searchRankSql = null;
if (!string.IsNullOrWhiteSpace(model.SearchKeyword) || model.SearchFilters?.Count > 0)
{
var (searchWhereSql, rankSql) = SqlHelper.BuildFilter(
model.RootType,
model.SearchKeyword,
model.SearchFilters == null ? null : new Dictionary<string, string>(model.SearchFilters, StringComparer.OrdinalIgnoreCase),
parameters,
dialect,
"t0",
model.SearchOptions);
if (!string.IsNullOrWhiteSpace(searchWhereSql))
whereParts.Add(searchWhereSql.Replace("WHERE ", string.Empty));
searchRankSql = rankSql;
}
var whereSql = whereParts.Count == 0
? string.Empty
: " WHERE " + string.Join(" AND ", whereParts);
var orderParts = model.Orders
.Select(o => SqlHelper.BuildOrderBy(o.Expression, model.RootType, "t0", o.Desc, dialect))
.ToList();
if (!string.IsNullOrWhiteSpace(searchRankSql))
orderParts.Insert(0, $"{searchRankSql} DESC");
var orderSql = orderParts.Count == 0
? string.Empty
: " ORDER BY " + string.Join(", ", orderParts);
var hasPaging = model.Limit.HasValue || model.Offset.HasValue;
var sqlServerPagingNeedsOrderFallback =
hasPaging
&& orderParts.Count == 0
&& string.Equals(dialect.Name, "sqlserver", StringComparison.OrdinalIgnoreCase);
var pagingSql = SqlHelper.BuildPaging(
model.Limit,
model.Offset,
dialect,
forceOrderByForSqlServer: sqlServerPagingNeedsOrderFallback);
var paging = string.IsNullOrWhiteSpace(pagingSql) ? string.Empty : " " + pagingSql;
var rootMap = SQLMapper.Get(model.RootType);
var includePlans = BuildNestedIncludePlans(model.RootType, model.Includes);
var selectSql = BuildNestedSelectSql(rootMap, includePlans, dialect);
var baseSql = $"{selectSql} {fromSql}{whereSql}";
var sql = mode switch
{
SqlQueryResultMode.List => $"{baseSql}{orderSql}{paging}",
SqlQueryResultMode.First => BuildFirstSql(baseSql, orderSql, dialect),
_ => throw new NotSupportedException($"Unsupported nested mode: {mode}")
};
return new NestedCompiledQuery(sql, parameters, rootMap, includePlans);
}
public static T MapNestedRow<T>(object row, NestedCompiledQuery compiled)
{
var values = row switch
{
IDictionary<string, object> typed => typed.ToDictionary(k => k.Key, v => (object?)v.Value, StringComparer.OrdinalIgnoreCase),
IDictionary nonGeneric => nonGeneric.Keys.Cast<object>()
.ToDictionary(k => k.ToString() ?? string.Empty, k => nonGeneric[k], StringComparer.OrdinalIgnoreCase),
_ => throw new InvalidOperationException("Nested mapping expects dictionary-backed Dapper rows.")
};
var root = Activator.CreateInstance<T>()
?? throw new InvalidOperationException($"Could not create instance of {typeof(T).Name}.");
foreach (var prop in compiled.RootMap.Selectable)
{
var key = $"root__{prop.Property.Name}";
if (values.TryGetValue(key, out var value))
AssignPropertyValue(root, prop.Property, value);
}
foreach (var include in compiled.Includes)
{
var includeInstance = Activator.CreateInstance(include.Map.EntityType);
if (includeInstance == null)
continue;
var hasAnyValue = false;
foreach (var includeProp in include.Map.Selectable)
{
var key = $"inc__{include.Alias}__{includeProp.Property.Name}";
if (!values.TryGetValue(key, out var value))
continue;
if (value is not null and not DBNull)
hasAnyValue = true;
AssignPropertyValue(includeInstance, includeProp.Property, value);
}
if (hasAnyValue)
include.NavigationProperty.SetValue(root, includeInstance);
}
return root;
}
private static string BuildProjectionSelectSql(
Type rootType,
IReadOnlyList<IncludeSpec> includes,
Type projectionType,
ISqlDialect dialect,
string alias)
{
var includeSignature = includes.Count == 0
? "none"
: string.Join(";", includes.Select(i =>
{
var navName = ExtractPropertyInfo(i.Navigation).Name;
return $"{i.JoinType.FullName}:{i.JoinKind}:{i.Alias ?? "(auto)"}:{navName}";
}));
var cacheKey = $"{dialect.Name}|{rootType.FullName}|{projectionType.FullName}|{alias}|{includeSignature}";
return ProjectionSelectCache.GetOrAdd(cacheKey, _ =>
{
var projectionMap = SQLMapper.Get(projectionType);
var sources = BuildProjectionSources(rootType, includes, alias);
var selectColumns = new List<string>();
foreach (var projectionProp in projectionMap.Selectable)
{
var matches = sources
.SelectMany(source => source.Map.Selectable
.Where(prop => prop.Column.Equals(projectionProp.Column, StringComparison.OrdinalIgnoreCase))
.Select(prop => (source, prop)))
.ToList();
if (matches.Count == 0)
throw new InvalidOperationException(
$"Projection property '{projectionProp.Property.Name}' ({projectionProp.Column}) does not map to any selectable source in query root/includes.");
var selected = ResolveProjectionMatch(matches, projectionProp, rootType);
selectColumns.Add($"{selected.source.Alias}.{dialect.Quote(selected.prop.Column)} AS {dialect.Quote(projectionProp.Property.Name)}");
}
if (selectColumns.Count == 0)
throw new InvalidOperationException($"Projection type '{projectionType.Name}' has no selectable properties.");
return "SELECT " + string.Join(", ", selectColumns);
});
}
private static IReadOnlyList<ProjectionSource> BuildProjectionSources(
Type rootType,
IReadOnlyList<IncludeSpec> includes,
string rootAlias)
{
var sources = new List<ProjectionSource>
{
new(rootAlias, rootType, SQLMapper.Get(rootType))
};
for (var includeIndex = 0; includeIndex < includes.Count; includeIndex++)
{
var include = includes[includeIndex];
var navProp = ExtractPropertyInfo(include.Navigation);
var relation = navProp.GetCustomAttribute<DbRelationAttribute>()
?? throw new InvalidOperationException($"Property {navProp.Name} is missing [DbRelation].");
if (relation.RelatedType != include.JoinType)
throw new InvalidOperationException($"[DbRelation] type mismatch on {navProp.Name}. Expected {include.JoinType.Name}.");
var resolvedAlias = include.Alias ?? relation.Alias ?? $"t{includeIndex + 1}";
if (sources.Any(s => string.Equals(s.Alias, resolvedAlias, StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException($"Duplicate include alias '{resolvedAlias}' detected.");
sources.Add(new ProjectionSource(
resolvedAlias,
include.JoinType,
SQLMapper.Get(include.JoinType)));
}
return sources;
}
private static PropertyInfo ExtractPropertyInfo(LambdaExpression expression)
{
return expression.Body switch
{
MemberExpression m when m.Member is PropertyInfo p => p,
UnaryExpression { Operand: MemberExpression m } when m.Member is PropertyInfo p => p,
_ => throw new InvalidOperationException("Navigation expression must target a property.")
};
}
private static IReadOnlyList<NestedIncludePlan> BuildNestedIncludePlans(
Type rootType,
IReadOnlyList<IncludeSpec> includes)
{
var plans = new List<NestedIncludePlan>();
for (var includeIndex = 0; includeIndex < includes.Count; includeIndex++)
{
var include = includes[includeIndex];
var navProp = ExtractPropertyInfo(include.Navigation);
var relation = navProp.GetCustomAttribute<DbRelationAttribute>()
?? throw new InvalidOperationException($"Property {navProp.Name} is missing [DbRelation].");
if (relation.RelatedType != include.JoinType)
throw new InvalidOperationException($"[DbRelation] type mismatch on {navProp.Name}. Expected {include.JoinType.Name}.");
var resolvedAlias = include.Alias ?? relation.Alias ?? $"t{includeIndex + 1}";
if (plans.Any(p => string.Equals(p.Alias, resolvedAlias, StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException($"Duplicate include alias '{resolvedAlias}' detected.");
plans.Add(new NestedIncludePlan(
resolvedAlias,
navProp,
SQLMapper.Get(include.JoinType)));
}
return plans;
}
private static string BuildNestedSelectSql(
SqlEntityMap rootMap,
IReadOnlyList<NestedIncludePlan> includes,
ISqlDialect dialect)
{
var cols = new List<string>();
foreach (var rootProp in rootMap.Selectable)
cols.Add($"t0.{dialect.Quote(rootProp.Column)} AS {dialect.Quote($"root__{rootProp.Property.Name}")}");
foreach (var include in includes)
{
foreach (var includeProp in include.Map.Selectable)
cols.Add($"{include.Alias}.{dialect.Quote(includeProp.Column)} AS {dialect.Quote($"inc__{include.Alias}__{includeProp.Property.Name}")}");
}
return "SELECT " + string.Join(", ", cols);
}
private static void AssignPropertyValue(object target, PropertyInfo property, object? rawValue)
{
if (rawValue is null or DBNull)
return;
var targetType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
var sourceType = rawValue.GetType();
object converted = targetType.IsAssignableFrom(sourceType)
? rawValue
: Convert.ChangeType(rawValue, targetType);
property.SetValue(target, converted);
}
private readonly record struct ProjectionSource(string Alias, Type ModelType, SqlEntityMap Map);
private static (ProjectionSource source, SqlPropertyMap prop) ResolveProjectionMatch(
IReadOnlyList<(ProjectionSource source, SqlPropertyMap prop)> matches,
SqlPropertyMap projectionProp,
Type rootType)
{
var hint = projectionProp.Property.GetCustomAttribute<ProjectionSourceAttribute>();
if (hint != null)
{
var hintedMatches = matches.Where(m =>
{
var aliasMatch = !string.IsNullOrWhiteSpace(hint.Alias)
&& string.Equals(m.source.Alias, hint.Alias, StringComparison.OrdinalIgnoreCase);
var typeMatch = hint.ModelType != null && m.source.ModelType == hint.ModelType;
return aliasMatch || typeMatch;
}).ToList();
if (hintedMatches.Count == 1)
return hintedMatches[0];
if (hintedMatches.Count == 0)
throw new InvalidOperationException(
$"Projection property '{projectionProp.Property.Name}' specifies [ProjectionSource] but no matching source was found.");
throw new InvalidOperationException(
$"Projection property '{projectionProp.Property.Name}' [ProjectionSource] matches multiple sources.");
}
var rootMatches = matches.Where(m => m.source.ModelType == rootType).ToList();
if (rootMatches.Count == 1)
return rootMatches[0];
if (matches.Count == 1)
return matches[0];
throw new InvalidOperationException(
$"Projection property '{projectionProp.Property.Name}' ({projectionProp.Column}) is ambiguous. Add [ProjectionSource(typeof(...))] or [ProjectionSource(\"alias\")].");
}
private static string BuildFirstSql(string baseQuerySql, string orderSql, ISqlDialect dialect)
{
if (string.Equals(dialect.Name, "sqlserver", StringComparison.OrdinalIgnoreCase))
{
const string token = "SELECT ";
return baseQuerySql.StartsWith(token, StringComparison.Ordinal)
? $"SELECT TOP 1 {baseQuerySql[token.Length..]}{orderSql}"
: $"SELECT TOP 1 * FROM ({baseQuerySql}) t{orderSql}";
}
return $"{baseQuerySql}{orderSql} LIMIT 1";
}
private static string BuildExistsSql(string fromSql, string whereSql, ISqlDialect dialect)
{
if (string.Equals(dialect.Name, "sqlserver", StringComparison.OrdinalIgnoreCase))
return $"SELECT CASE WHEN EXISTS (SELECT 1 {fromSql}{whereSql}) THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END";
return $"SELECT EXISTS (SELECT 1 {fromSql}{whereSql})";
}
private static object CreateTypedQuery(Type rootType, ISqlDialect dialect)
{
var queryType = typeof(SqlQuery<>).MakeGenericType(rootType);
return Activator.CreateInstance(queryType, "t0", dialect)
?? throw new InvalidOperationException($"Failed to create SqlQuery for type {rootType.Name}.");
}
private static object ApplyInclude(object query, IncludeSpec include)
{
var queryType = query.GetType();
var method = queryType
.GetMethods(BindingFlags.Public | BindingFlags.Instance)
.FirstOrDefault(m =>
m.Name == nameof(SqlQuery<object>.Include)
&& m.IsGenericMethodDefinition
&& m.GetParameters().Length == 3)
?? throw new InvalidOperationException("Could not locate Include method.");
var genericInclude = method.MakeGenericMethod(include.JoinType);
try
{
return genericInclude.Invoke(query, [include.Navigation, include.JoinKind, include.Alias])
?? throw new InvalidOperationException("Failed to apply include.");
}
catch (TargetInvocationException ex) when (ex.InnerException != null)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
throw;
}
}
}
internal static class SqlWriteCompiler
{
internal readonly record struct UpsertPlan(string Sql, IReadOnlyList<SqlPropertyMap> InsertProps);
public static UpsertPlan BuildUpsertPlan<T>(Expression<Func<T, object>> keySelector, ISqlDialect dialect)
{
var map = SQLMapper.Get<T>();
var keys = ResolveKeyProperties(keySelector, map);
if (keys.Count == 0)
throw new InvalidOperationException("Upsert requires at least one key column.");