forked from dotnet/SqlClient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CopyAllFromReaderAsync.cs
68 lines (60 loc) · 2.97 KB
/
CopyAllFromReaderAsync.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.Data.SqlClient.ManualTesting.Tests
{
public class CopyAllFromReaderAsync
{
public static void Test(string srcConstr, string dstConstr, string dstTable)
{
// Use this semaphore to ensure that results are written to the log in the correct order
SemaphoreSlim outputSemaphore = new SemaphoreSlim(0, 1);
Task t = TestAsync(srcConstr, dstConstr, dstTable, outputSemaphore);
outputSemaphore.Release();
t.Wait();
Assert.True(t.IsCompleted, "Task did not complete! Status: " + t.Status);
}
private static async Task TestAsync(string srcConstr, string dstConstr, string dstTable, SemaphoreSlim outputSemaphore)
{
string initialQueryTemplate = "create table {0} (col1 int, col2 nvarchar(20), col3 nvarchar(10))";
string sourceQueryTemplate = "select top 5 EmployeeID, LastName, FirstName from {0}";
string srcTable = "employees";
string sourceQuery = string.Format(sourceQueryTemplate, srcTable);
string initialQuery = string.Format(initialQueryTemplate, dstTable);
using (SqlConnection dstConn = new SqlConnection(dstConstr))
using (SqlCommand dstCmd = dstConn.CreateCommand())
{
dstConn.Open();
try
{
Helpers.TryExecute(dstCmd, initialQuery);
using (SqlConnection srcConn = new SqlConnection(srcConstr))
using (SqlCommand srcCmd = new SqlCommand(sourceQuery, srcConn))
{
srcConn.Open();
using (DbDataReader reader = srcCmd.ExecuteReader())
{
using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
{
bulkcopy.DestinationTableName = dstTable;
await bulkcopy.WriteToServerAsync(reader);
await outputSemaphore.WaitAsync();
DataTestUtility.AssertEqualsWithDescription(bulkcopy.RowsCopied, 5, "Unexpected number of rows.");
DataTestUtility.AssertEqualsWithDescription(bulkcopy.RowsCopied64, (long)5, "Unexpected number of rows.");
}
Helpers.VerifyResults(dstConn, dstTable, 3, 5);
}
}
}
finally
{
Helpers.TryExecute(dstCmd, "drop table " + dstTable);
}
}
}
}
}