forked from ThatRendle/Simple.Data
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBulkInserter.cs
More file actions
61 lines (51 loc) · 2.69 KB
/
BulkInserter.cs
File metadata and controls
61 lines (51 loc) · 2.69 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
namespace Simple.Data.Ado
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using Schema;
public class BulkInserter : IBulkInserter
{
public IEnumerable<IDictionary<string, object>> Insert(AdoAdapter adapter, string tableName, IEnumerable<IDictionary<string, object>> data, IDbTransaction transaction, Func<IDictionary<string,object>, Exception, bool> onError, bool resultRequired)
{
var table = adapter.GetSchema().FindTable(tableName);
var columns = table.Columns.Where(c => c.IsWriteable).ToList();
string columnList = string.Join(",", columns.Select(c => c.QuotedName));
string valueList = string.Join(",", columns.Select(c => "?"));
string insertSql = "insert into " + table.QualifiedName + " (" + columnList + ") values (" + valueList + ")";
var helper = transaction == null
? new BulkInserterHelper(adapter, data, table, columns)
: new BulkInserterTransactionHelper(adapter, data, table, columns, transaction);
if (resultRequired)
{
var identityColumn = table.Columns.FirstOrDefault(col => col.IsIdentity);
if (identityColumn != null)
{
var identityFunction = adapter.GetIdentityFunction();
if (!string.IsNullOrWhiteSpace(identityFunction))
{
return InsertRowsAndReturn(adapter, identityFunction, helper, insertSql, table, onError);
}
}
}
helper.InsertRowsWithoutFetchBack(insertSql, onError);
return null;
}
private static IEnumerable<IDictionary<string, object>> InsertRowsAndReturn(AdoAdapter adapter, string identityFunction, BulkInserterHelper helper, string insertSql, Table table, Func<IDictionary<string, object>, Exception, bool> onError)
{
var identityColumn = table.Columns.FirstOrDefault(col => col.IsIdentity);
if (identityColumn != null)
{
var selectSql = "select * from " + table.QualifiedName + " where " + identityColumn.QuotedName +
" = " + identityFunction;
if (adapter.ProviderSupportsCompoundStatements)
{
return helper.InsertRowsWithCompoundStatement(insertSql, selectSql, onError);
}
return helper.InsertRowsWithSeparateStatements(insertSql, selectSql, onError);
}
return null;
}
}
}