forked from ThatRendle/Simple.Data
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqlObservableQueryRunner.cs
More file actions
74 lines (66 loc) · 2.73 KB
/
Copy pathSqlObservableQueryRunner.cs
File metadata and controls
74 lines (66 loc) · 2.73 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Simple.Data.SqlServer
{
using System.ComponentModel.Composition;
using System.Data;
using System.Data.SqlClient;
using Ado;
[Export(typeof(IObservableQueryRunner))]
public class SqlObservableQueryRunner : IObservableQueryRunner
{
public IObservable<IDictionary<string, object>> Run(IDbCommand command, IDbConnection connection, IDictionary<string, int> index)
{
return new SqlObservable(connection as SqlConnection, command as SqlCommand, index);
}
class SqlObservable : IObservable<IDictionary<string,object>>
{
private readonly SqlConnection _connection;
private readonly SqlCommand _command;
private IDictionary<string, int> _index;
public SqlObservable(SqlConnection connection, SqlCommand command, IDictionary<string,int> index)
{
if (connection == null) throw new ArgumentNullException("connection");
if (command == null) throw new ArgumentNullException("command");
_connection = connection;
_command = command;
_index = index;
}
public IDisposable Subscribe(IObserver<IDictionary<string, object>> observer)
{
if (_connection.State == ConnectionState.Closed)
{
_connection.Open();
}
_command.BeginExecuteReader(ExecuteReaderCompleted, observer);
return new ActionDisposable(() =>
{
using (_connection) using (_command) { }
});
}
private void ExecuteReaderCompleted(IAsyncResult ar)
{
var observer = ar.AsyncState as IObserver<IDictionary<string, object>>;
if (observer == null) throw new InvalidOperationException();
try
{
using (var reader = _command.EndExecuteReader(ar))
{
if (_index == null) _index = reader.CreateDictionaryIndex();
while (reader.Read())
{
observer.OnNext(reader.ToDictionary(_index));
}
}
observer.OnCompleted();
}
catch (Exception ex)
{
observer.OnError(ex);
}
}
}
}
}