forked from PhenX/PhenX.EntityFrameworkCore.BulkInsert
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostgreSqlBulkInsertProvider.cs
More file actions
97 lines (80 loc) · 2.91 KB
/
PostgreSqlBulkInsertProvider.cs
File metadata and controls
97 lines (80 loc) · 2.91 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
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Npgsql;
using PhenX.EntityFrameworkCore.BulkInsert.Metadata;
using PhenX.EntityFrameworkCore.BulkInsert.Options;
namespace PhenX.EntityFrameworkCore.BulkInsert.PostgreSql;
[UsedImplicitly]
internal class PostgreSqlBulkInsertProvider : BulkInsertProviderBase<PostgreSqlDialectBuilder>
{
public PostgreSqlBulkInsertProvider(ILogger<PostgreSqlBulkInsertProvider>? logger = null) : base(logger)
{
}
//language=sql
/// <inheritdoc />
protected override string CreateTableCopySql => "CREATE TEMPORARY TABLE {0} AS TABLE {1} WITH NO DATA;";
//language=sql
/// <inheritdoc />
protected override string AddTableCopyBulkInsertId => $"ALTER TABLE {{0}} ADD COLUMN {BulkInsertId} SERIAL PRIMARY KEY;";
private static string GetBinaryImportCommand(TableMetadata tableInfo, string tableName)
{
var columns = tableInfo.GetProperties(false).Select(X => X.QuotedColumName);
return $"COPY {tableName} ({string.Join(", ", columns)}) FROM STDIN (FORMAT BINARY)";
}
/// <inheritdoc />
protected override async Task BulkInsert<T>(
bool sync,
DbContext context,
TableMetadata tableInfo,
IEnumerable<T> entities,
string tableName,
IReadOnlyList<PropertyMetadata> properties,
BulkInsertOptions options,
CancellationToken ctk)
{
var connection = (NpgsqlConnection)context.Database.GetDbConnection();
var importCommand = GetBinaryImportCommand(tableInfo, tableName);
var writer = sync
// ReSharper disable once MethodHasAsyncOverloadWithCancellation
? connection.BeginBinaryImport(importCommand)
: await connection.BeginBinaryImportAsync(importCommand, ctk);
foreach (var entity in entities)
{
if (sync)
{
// ReSharper disable once MethodHasAsyncOverloadWithCancellation
writer.StartRow();
}
else
{
await writer.StartRowAsync(ctk);
}
foreach (var property in properties)
{
var value = property.GetValue(entity);
if (sync)
{
// ReSharper disable once MethodHasAsyncOverloadWithCancellation
writer.Write(value);
}
else
{
await writer.WriteAsync(value, ctk);
}
}
}
if (sync)
{
// ReSharper disable once MethodHasAsyncOverloadWithCancellation
writer.Complete();
// ReSharper disable once MethodHasAsyncOverload
writer.Dispose();
}
else
{
await writer.CompleteAsync(ctk);
await writer.DisposeAsync();
}
}
}