-
Notifications
You must be signed in to change notification settings - Fork 520
Expand file tree
/
Copy pathExtensions.cs
More file actions
214 lines (179 loc) · 6.95 KB
/
Extensions.cs
File metadata and controls
214 lines (179 loc) · 6.95 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
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.Extensions.DependencyInjection;
using PhenX.EntityFrameworkCore.BulkInsert.Extensions;
using PhenX.EntityFrameworkCore.BulkInsert.Options;
using Squidex.Domain.Apps.Entities;
using Squidex.Infrastructure.Queries;
using Squidex.Infrastructure.States;
namespace Squidex.Infrastructure;
public static class Extensions
{
public static IServiceCollection AddNamedDbContext<TContext>(this IServiceCollection services,
Action<DbContextOptionsBuilder<TContext>, string> configure)
where TContext : DbContext
{
services.AddSingleton<IDbContextNamedFactory<TContext>>(c =>
ActivatorUtilities.CreateInstance<PooledDbNamedContextFactory<TContext>>(c, configure));
return services;
}
public static DbContextOptionsBuilder<TContext> UsePrefix<TContext>(this DbContextOptionsBuilder<TContext> builder, string prefix)
where TContext : DbContext
{
((IDbContextOptionsBuilderInfrastructure)builder).AddOrUpdateExtension(new PrefixExtension(prefix));
return builder;
}
public static DbContextOptionsBuilder<TContext> UsePoolSize<TContext>(this DbContextOptionsBuilder<TContext> builder, int poolSize)
where TContext : DbContext
{
var extension =
(builder.Options.FindExtension<CoreOptionsExtension>() ?? new CoreOptionsExtension())
.WithMaxPoolSize(poolSize);
((IDbContextOptionsBuilderInfrastructure)builder).AddOrUpdateExtension(extension);
return builder;
}
public static string Prefix(this DbContextOptions options)
{
return options.GetExtension<PrefixExtension>().Prefix;
}
public static DbContextOptionsBuilder SetDefaultWarnings(this DbContextOptionsBuilder builder)
{
builder.ConfigureWarnings(w => w.Ignore(CoreEventId.CollectionWithoutComparer));
return builder;
}
public static IQueryable<T> Pagination<T>(this IQueryable<T> source, ClrQuery query)
{
if (query.Skip > 0)
{
source = source.Skip((int)query.Skip);
}
if (query.Take < long.MaxValue)
{
source = source.Take((int)query.Take);
}
return source;
}
public static IQueryable<T> WhereIf<T>(this IQueryable<T> source, Expression<Func<T, bool>> predicate, bool valid)
{
if (!valid)
{
return source;
}
return source.Where(predicate);
}
public static Task BulkUpsertAsync<T>(this DbContext dbContext, List<T> source,
CancellationToken ct) where T : class
{
if (source.Count == 0)
{
return Task.CompletedTask;
}
return dbContext.ExecuteBulkInsertAsync(source, o => { }, new OnConflictOptions<T> { Update = e => e }, ct);
}
public static Task BulkInsertAsync<T>(this DbContext dbContext, List<T> source,
CancellationToken ct) where T : class
{
if (source.Count == 0)
{
return Task.CompletedTask;
}
return dbContext.ExecuteBulkInsertAsync(source, cancellationToken: ct);
}
public static async Task<IResultList<T>> QueryAsync<T>(this IQueryable<T> queryable, Q q,
CancellationToken ct) where T : class
{
var query = q.Query;
var queryEntities = await queryable.Pagination(q.Query).ToListAsync(ct);
var queryTotal = (long)queryEntities.Count;
if (queryEntities.Count >= query.Take || query.Skip > 0)
{
if (q.NoTotal)
{
queryTotal = -1;
}
else
{
queryTotal = await queryable.CountAsync(ct);
}
}
if (q.Query.Random > 0)
{
queryEntities = queryEntities.TakeRandom(q.Query.Random).ToList();
}
return ResultList.Create(queryTotal, queryEntities.OfType<T>());
}
public static async Task<IResultList<T>> QueryAsync<T>(this DbContext dbContext, SqlQueryBuilder sqlQuery, Q q,
CancellationToken ct) where T : class
{
sqlQuery.Limit(q.Query);
sqlQuery.Offset(q.Query);
sqlQuery.Order(q.Query);
sqlQuery.Where(q.Query);
var (sql, parameters) = sqlQuery.Compile();
var queryEntities = await dbContext.Set<T>().FromSqlRaw(sql, parameters).ToListAsync(ct);
var queryTotal = (long)queryEntities.Count;
if (queryEntities.Count >= q.Query.Take || q.Query.Skip > 0)
{
if (q.NoTotal || q.NoSlowTotal)
{
queryTotal = -1;
}
else
{
var (countSql, countParams) = sqlQuery.Count().Compile();
queryTotal =
await dbContext.Database.SqlQueryRaw<int>(countSql, countParams)
.FirstOrDefaultAsync(ct);
}
}
if (q.Query.Random > 0)
{
queryEntities = queryEntities.TakeRandom(q.Query.Random).ToList();
}
return ResultList.Create(queryTotal, queryEntities.OfType<T>());
}
public static async Task UpsertAsync<T>(this DbContext dbContext, T entity, long oldVersion,
Func<T, Expression<Func<SetPropertyCalls<T>, SetPropertyCalls<T>>>> update,
CancellationToken ct) where T : class, IVersionedEntity<DomainId>
{
var dbSet = dbContext.Set<T>();
try
{
await dbSet.AddAsync(entity, ct);
await dbContext.SaveChangesAsync(ct);
}
catch (DbUpdateException)
{
var updateQuery = dbSet.Where(x => x.DocumentId == entity.DocumentId);
if (oldVersion > EtagVersion.Any)
{
updateQuery = updateQuery.Where(x => x.Version == oldVersion);
}
var updateCount =
await updateQuery
.ExecuteUpdateAsync(update(entity), ct);
if (updateCount != 1)
{
var currentVersions =
await dbSet
.Where(x => x.DocumentId == entity.DocumentId).Select(x => x.Version)
.ToListAsync(ct);
var current = currentVersions.Count == 1 ? currentVersions[0] : EtagVersion.Empty;
throw new InconsistentStateException(current, oldVersion);
}
}
finally
{
dbContext.Entry(entity).State = EntityState.Detached;
}
}
}