|
| 1 | +using ClickHouse.Client.Copy; |
| 2 | +using Microsoft.Extensions.Options; |
| 3 | + |
| 4 | +namespace Cnblogs.Architecture.Ddd.Infrastructure.Dapper.Clickhouse; |
| 5 | + |
| 6 | +/// <summary> |
| 7 | +/// DapperContext that specialized for clickhouse. |
| 8 | +/// </summary> |
| 9 | +public abstract class ClickhouseDapperContext : DapperContext |
| 10 | +{ |
| 11 | + private readonly ClickhouseContextOptions _options; |
| 12 | + |
| 13 | + /// <summary> |
| 14 | + /// Create a <see cref="ClickhouseDapperContext"/>. |
| 15 | + /// </summary> |
| 16 | + /// <param name="dbConnectionFactoryCollection">The underlying <see cref="IDbConnectionFactory"/> collection.</param> |
| 17 | + /// <param name="options">The options used for this context.</param> |
| 18 | + protected ClickhouseDapperContext( |
| 19 | + IOptions<DbConnectionFactoryCollection> dbConnectionFactoryCollection, |
| 20 | + ClickhouseContextOptions options) |
| 21 | + : base(dbConnectionFactoryCollection) |
| 22 | + { |
| 23 | + _options = options; |
| 24 | + } |
| 25 | + |
| 26 | + /// <summary> |
| 27 | + /// Init context, register models, etc. |
| 28 | + /// </summary> |
| 29 | + public void Init() |
| 30 | + { |
| 31 | + var builder = new ClickhouseModelCollectionBuilder(); |
| 32 | + ConfigureModels(builder); |
| 33 | + builder.Build(_options); |
| 34 | + } |
| 35 | + |
| 36 | + /// <summary> |
| 37 | + /// Configure models that related to this context. |
| 38 | + /// </summary> |
| 39 | + /// <param name="builder"><see cref="ClickhouseModelCollectionBuilder"/>.</param> |
| 40 | + protected abstract void ConfigureModels(ClickhouseModelCollectionBuilder builder); |
| 41 | + |
| 42 | + /// <summary> |
| 43 | + /// Bulk write entities to clickhouse. |
| 44 | + /// </summary> |
| 45 | + /// <param name="entities">The entity to be written.</param> |
| 46 | + /// <typeparam name="T">The type of entity.</typeparam> |
| 47 | + /// <exception cref="InvalidOperationException">Throw when <typeparamref name="T"/> is not registered.</exception> |
| 48 | + public async Task BulkWriteAsync<T>(IEnumerable<T> entities) |
| 49 | + where T : class |
| 50 | + { |
| 51 | + var configuration = _options.GetConfiguration<T>(); |
| 52 | + if (configuration is null) |
| 53 | + { |
| 54 | + throw new InvalidOperationException( |
| 55 | + $"The model type {typeof(T).Name} is not registered, make sure you have called builder.Entity<T>() at ConfigureModels()"); |
| 56 | + } |
| 57 | + |
| 58 | + using var bulkCopyInterface = new ClickHouseBulkCopy(_options.ConnectionString) |
| 59 | + { |
| 60 | + DestinationTableName = configuration.TableName |
| 61 | + }; |
| 62 | + |
| 63 | + var objs = entities.Select(x => configuration.ToObjectArray(x)); |
| 64 | + await bulkCopyInterface.WriteToServerAsync(objs, configuration.ColumnNames); |
| 65 | + } |
| 66 | +} |
0 commit comments