zhaolei
2020-11-20 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
using PetaPoco.Core;
using System;
using System.Collections.Generic;
using System.Linq;
 
namespace PetaPoco
{
    internal class OracleBatchProvider : BatchProvider
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public OracleBatchProvider(IDatabase db) : base(db)
        {
            BatchSize = 50;
        }
 
        /// <summary>
        /// 拼接字符串方法具体实现
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pd"></param>
        /// <param name="pocos"></param>
        protected override void InsertBatch<T>(PocoData pd, IEnumerable<T> pocos)
        {
            try
            {
                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();
 
                // Oracle 批量插入获得到当前表序列值
                var index = 0;
                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;
 
                        // 是否为自增长主键序列
                        if (autoIncrement && primaryKeyName != null && primaryKeyName.Equals(i.Key, StringComparison.OrdinalIgnoreCase))
                        {
                            // Setup auto increment expression
                            if (index == 0)
                            {
                                // index == 0 表示未获取主键起始值
                                var autoIncExpression = _provider.GetAutoIncrementExpression(pd.TableInfo);
                                if (autoIncExpression != null)
                                {
                                    index = Database.ExecuteScalar<int>($"select {autoIncExpression} from dual");
                                    if (index == 0) throw new Exception("");
                                }
                            }
                            names.Add(Database.Provider.EscapeTableName(i.Key));
                            values.Add(index.ToString());
                            index++;
                            continue;
                        }
 
                        names.Add(_provider.EscapeSqlIdentifier(i.Key));
                        values.Add(ConvertValue(i.Value.GetValue(poco), args));
                    }
                    if (batchSql.Count == 0)
                    {
                        batchSql.Add("INSERT ALL");
                    }
                    batchSql.Add(GenerateBodySql(Database.Provider.EscapeTableName(pd.TableInfo.TableName), names.ToArray(), values.ToArray()));
 
                    if (batchSql.Count == BatchSize)
                    {
                        InsertIntoDb(batchSql, args);
                    }
                });
 
                // 剩余数据
                if (batchSql.Count > 0) InsertIntoDb(batchSql, args);
 
                // 更新主键序列
                if (index != 0 && pocos.Count() > 1)
                {
                    var seqName = pd.TableInfo.SequenceName;
                    Database.Execute($"ALTER SEQUENCE {seqName} INCREMENT BY {pocos.Count() - 1}");
                    var seq = Database.ExecuteScalar<int>($"SELECT {seqName}.NEXTVAL FROM DUAL");
                    Database.Execute($"ALTER SEQUENCE {seqName} INCREMENT BY 1");
                }
                Database.CompleteTransaction();
            }
            catch (Exception)
            {
                Database.AbortTransaction();
                throw;
            }
        }
 
        /// <summary>
        /// 生成插入语句方法
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="names"></param>
        /// <param name="values"></param>
        /// <returns></returns>
        protected string GenerateBodySql(string tableName, string[] names, string[] values)
        {
            return $" INTO {tableName} ({string.Join(",", names)}) Values ({string.Join(",", values)})";
        }
 
        protected override void InsertIntoDb(List<string> sqls, List<object> args)
        {
            sqls.Add(" select 1 from dual");
            base.InsertIntoDb(sqls, args);
        }
    }
}