zhaolei
7 days ago 921de2254ff5712a44ed8575ee8efe34252f6603
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
using PetaPoco.Core;
using PetaPoco.Providers;
using System;
using System.Collections.Generic;
using System.Linq;
 
namespace PetaPoco
{
    /// <summary>
    /// 内部批次方法提供者实现类
    /// </summary>
    internal class BatchProvider
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db">IDatabase 实例</param>
        public BatchProvider(IDatabase db)
        {
            Database = db;
        }
 
        /// <summary>
        /// 创建 BatchProvider 实例
        /// </summary>
        /// <param name="db">IDatabase 实例</param>
        /// <returns></returns>
        public static BatchProvider Create(IDatabase db) => db.Provider.GetType().Name switch
        {
            nameof(SqlServerDatabaseProvider) => new SqlServerBatchProvider(db),
            nameof(SQLiteDatabaseProvider) => new SQLiteBatchProvider(db),
            nameof(OracleDatabaseProvider) => new OracleBatchProvider(db),
            _ => new BatchProvider(db)
        };
 
        /// <summary>
        /// 获得 IDatabase 实例
        /// </summary>
        public IDatabase Database { get; }
 
        /// <summary>
        /// 获得/设置 每批实体大小,此值通过测试得出相对插入速度比较快的一个值 默认 50
        /// </summary>
        public int BatchSize { get; protected set; } = 50;
 
        /// <summary>
        /// 获得/设置 是否支持批量插入功能
        /// </summary>
        public bool SupportBulk { get; set; }
 
        /// <summary>
        /// 批次插入方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pocos"></param>
        public virtual void InsertBatch<T>(IEnumerable<T> pocos)
        {
            if (SupportBulk)
            {
                InsertBulk(pocos);
            }
            else
            {
                var pd = PocoData.ForType(typeof(T), Database.DefaultMapper);
                InsertBatch(pd, pocos);
            }
        }
 
        /// <summary>
        /// 批次插入方法
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="primaryKeyName"></param>
        /// <param name="autoIncrement"></param>
        /// <param name="pocos"></param>
        public virtual void InsertBatch(string tableName, string primaryKeyName, bool autoIncrement, IEnumerable<object> pocos)
        {
            if (SupportBulk)
            {
                InsertBulk(tableName, primaryKeyName, autoIncrement, pocos);
            }
            else
            {
                var pd = PocoData.ForType(pocos.First().GetType(), Database.DefaultMapper);
                if (!string.IsNullOrEmpty(tableName)) pd.TableInfo.TableName = tableName;
                if (!string.IsNullOrEmpty(primaryKeyName)) pd.TableInfo.PrimaryKey = primaryKeyName;
                if (autoIncrement) pd.TableInfo.AutoIncrement = autoIncrement;
                InsertBatch(pd, pocos);
            }
        }
 
        /// <summary>
        /// Bulk批次插入方法具体实现
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pocos"></param>
        protected virtual void InsertBulk<T>(IEnumerable<T> pocos) => throw new NotImplementedException();
 
        /// <summary>
        /// Bulk批次插入方法具体实现
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="primaryKeyName"></param>
        /// <param name="autoIncrement"></param>
        /// <param name="pocos"></param>
        protected virtual void InsertBulk(string tableName, string primaryKeyName, bool autoIncrement, IEnumerable<object> pocos) => throw new NotImplementedException();
 
        /// <summary>
        /// 拼接字符串方法具体实现
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pd"></param>
        /// <param name="pocos"></param>
        protected virtual void InsertBatch<T>(PocoData pd, IEnumerable<T> pocos)
        {
            try
            {
                /*
                 * 将 entities 分批插入数据库
                 * 每批生成 insert into TableName(...) values(...),(...)... 
                 * 该方法相对循环一条一条插入,速度提升 2/3 这样
                 */
 
                var primaryKeyName = pd.TableInfo.PrimaryKey;
                var autoIncrement = pd.TableInfo.AutoIncrement;
                var _provider = Database.Provider;
                var args = new List<object>();
                var batchSql = new List<string>();
 
                Database.BeginTransaction();
                pocos.ToList().ForEach(poco =>
                {
                    var names = new List<string>();
                    var values = new List<string>();
                    foreach (var i in pd.Columns)
                    {
                        // Don't insert result columns
                        if (i.Value.ResultColumn)
                            continue;
 
                        // Don't insert the primary key (except under oracle where we need bring in the next sequence value)
                        if (autoIncrement && primaryKeyName != null && primaryKeyName.Equals(i.Key, StringComparison.OrdinalIgnoreCase))
                        {
                            // Setup auto increment expression
                            var autoIncExpression = _provider.GetAutoIncrementExpression(pd.TableInfo);
                            if (autoIncExpression != null)
                            {
                                names.Add(i.Key);
                                values.Add(autoIncExpression);
                            }
                            continue;
                        }
 
                        names.Add(_provider.EscapeSqlIdentifier(i.Key));
                        values.Add(ConvertValue(i.Value.GetValue(poco), args));
                    }
                    if (batchSql.Count == 0)
                    {
                        batchSql.Add(GenerateHeaderSql(Database.Provider.EscapeTableName(pd.TableInfo.TableName), names.ToArray(), values.ToArray()));
                    }
                    else
                    {
                        batchSql.Add(GenerateBodySql(values.ToArray()));
                    }
 
                    if (batchSql.Count == BatchSize)
                    {
                        InsertIntoDb(batchSql, args);
                    }
                });
 
                // 剩余数据
                if (batchSql.Count > 0) InsertIntoDb(batchSql, args);
 
                Database.CompleteTransaction();
            }
            catch (Exception)
            {
                Database.AbortTransaction();
                throw;
            }
        }
 
        protected virtual void InsertIntoDb(List<string> sqls, List<object> args)
        {
            Database.Execute(string.Join("", sqls), args.ToArray());
            sqls.Clear();
            args.Clear();
        }
 
        protected virtual string GenerateHeaderSql(string tableName, string[] names, string[] values) => $"INSERT INTO {tableName} ({string.Join(",", names)}) VALUES ({string.Join(",", values)})";
 
        protected virtual string GenerateBodySql(string[] values) => $",({string.Join(",", values)})";
        /// <summary>
        /// 生成数据库插入语句
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="names"></param>
        /// <param name="values"></param>
        /// <returns></returns>
        protected virtual string GenerateSql(string tableName, string[] names, string[] values) => $"INSERT INTO {tableName} ({string.Join(",", names)}) VALUES ({string.Join(",", values)})";
 
        /// <summary>
        /// 数据类型转化方法
        /// </summary>
        /// <param name="val"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        protected virtual string ConvertValue(object val, List<object> args)
        {
            if (val == null) return "NULL";
            var valType = val.GetType();
            if (valType.IsEnum)
            {
                val = Convert.ChangeType(val, Enum.GetUnderlyingType(valType));
                valType = val.GetType();
            }
            if (Utils.IsToStringableNumericType(valType)) return val.ToString();
 
            if (val is bool) return Database.Provider.MapParameterValue(val).ToString();
            var ret = $"@{args.Count}";
            args.Add(val);
            return ret;
        }
    }
}