-
Notifications
You must be signed in to change notification settings - Fork 190
/
FreeSqlExtension.cs
297 lines (256 loc) · 10.6 KB
/
FreeSqlExtension.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
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
using System;
using System.Data;
using System.Data.Odbc;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using FreeSql;
using MySqlConnector;
using Npgsql;
using Serilog;
namespace LinCms.FreeSql;
public static class FreeSqlExtension
{
private static string GetConnectionString(this FreeSqlBuilder @this)
{
Type type = @this.GetType();
FieldInfo fieldInfo = type.GetField("_masterConnectionString", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo is null)
{
throw new ArgumentException("_masterConnectionString is null");
}
return fieldInfo.GetValue(@this).ToString();
}
#region CreateDatabaseIfNotExists
/// <summary>
/// 请在UseConnectionString配置后调用此方法
/// </summary>
/// <param name="this"></param>
/// <returns></returns>
public static FreeSqlBuilder CreateDatabaseIfNotExists(this FreeSqlBuilder @this)
{
FieldInfo dataTypeFieldInfo = @this.GetType().GetField("_dataType", BindingFlags.NonPublic | BindingFlags.Instance);
if (dataTypeFieldInfo is null)
{
throw new ArgumentException("_dataType is null");
}
string connectionString = GetConnectionString(@this);
DataType dbType = (DataType)dataTypeFieldInfo.GetValue(@this);
switch (dbType)
{
case DataType.MySql:
return @this.CreateDatabaseIfNotExistsMySql(connectionString);
case DataType.SqlServer:
return @this.CreateDatabaseIfNotExistsSqlServer(connectionString);
case DataType.PostgreSQL:
return @this.CreateDatabaseIfNotExistsPgSql(connectionString);
case DataType.Oracle:
break;
case DataType.Sqlite:
return @this;
case DataType.OdbcOracle:
break;
case DataType.OdbcSqlServer:
return @this.CreateDatabaseIfNotExists_ODBCSqlServer(connectionString);
case DataType.OdbcMySql:
return @this.CreateDatabaseIfNotExists_ODBCMySql(connectionString);
case DataType.OdbcPostgreSQL:
break;
case DataType.Odbc:
break;
case DataType.MsAccess:
break;
case DataType.Dameng:
break;
case DataType.ShenTong:
break;
case DataType.KingbaseES:
break;
case DataType.Firebird:
break;
case DataType.Custom:
break;
case DataType.ClickHouse:
break;
case DataType.GBase:
break;
default:
break;
}
Log.Error($"不支持创建数据库");
return @this;
}
#endregion
#region MySql
public static FreeSqlBuilder CreateDatabaseIfNotExistsMySql(this FreeSqlBuilder @this, string connectionString = "")
{
if (connectionString == "")
{
connectionString = GetConnectionString(@this);
}
MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder(connectionString);
string createDatabaseSql = $"USE mysql;CREATE DATABASE IF NOT EXISTS `{builder.Database}` CHARACTER SET '{builder.CharacterSet}' COLLATE 'utf8mb4_general_ci'";
using MySqlConnection cnn = new MySqlConnection($"Data Source={builder.Server};Port={builder.Port};User ID={builder.UserID};Password={builder.Password};Initial Catalog=mysql;Charset=utf8;SslMode=none;Max pool size=1");
cnn.Open();
using (MySqlCommand cmd = cnn.CreateCommand())
{
cmd.CommandText = createDatabaseSql;
cmd.ExecuteNonQuery();
}
return @this;
}
#endregion
#region SqlServer
public static FreeSqlBuilder CreateDatabaseIfNotExistsSqlServer(this FreeSqlBuilder @this, string connectionString = "")
{
if (connectionString == "")
{
connectionString = GetConnectionString(@this);
}
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
string createDatabaseSql;
if (!string.IsNullOrEmpty(builder.AttachDBFilename))
{
string fileName = ExpandFileName(builder.AttachDBFilename);
string name = Path.GetFileNameWithoutExtension(fileName);
string logFileName = Path.ChangeExtension(fileName, ".ldf");
createDatabaseSql = @$"CREATE DATABASE {builder.InitialCatalog} on primary
(
name = '{name}',
filename = '{fileName}'
)
log on
(
name= '{name}_log',
filename = '{logFileName}'
)";
}
else
{
createDatabaseSql = @$"CREATE DATABASE {builder.InitialCatalog}";
}
using SqlConnection cnn = new SqlConnection($"Data Source={builder.DataSource};Integrated Security = True;User ID={builder.UserID};Password={builder.Password};Initial Catalog=master;Min pool size=1");
cnn.Open();
using SqlCommand cmd = cnn.CreateCommand();
cmd.CommandText = $"select * from sysdatabases where name = '{builder.InitialCatalog}'";
SqlDataAdapter apter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
apter.Fill(ds);
if (ds.Tables[0].Rows.Count == 0)
{
cmd.CommandText = createDatabaseSql;
cmd.ExecuteNonQuery();
}
return @this;
}
private static string ExpandFileName(string fileName)
{
if (fileName.StartsWith("|DataDirectory|", StringComparison.OrdinalIgnoreCase))
{
var dataDirectory = AppDomain.CurrentDomain.GetData("DataDirectory") as string;
if (string.IsNullOrEmpty(dataDirectory))
{
dataDirectory = AppDomain.CurrentDomain.BaseDirectory;
}
string name = fileName.Replace("\\", "").Replace("/", "").Substring("|DataDirectory|".Length);
fileName = Path.Combine(dataDirectory, name);
}
if (!Directory.Exists(Path.GetDirectoryName(fileName)))
{
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
}
return Path.GetFullPath(fileName);
}
#endregion
#region PgSql
public static FreeSqlBuilder CreateDatabaseIfNotExistsPgSql(this FreeSqlBuilder @this, string connectionString = "")
{
if (connectionString == "")
{
connectionString = GetConnectionString(@this);
}
NpgsqlConnectionStringBuilder builder = new NpgsqlConnectionStringBuilder(connectionString);
string databaseExistSql = $"SELECT COUNT(*) FROM pg_database WHERE datname = '{builder.Database}'";
string createDatabaseSql = $"CREATE DATABASE \"{builder.Database}\" WITH OWNER = \"{builder.Username}\"";
using NpgsqlConnection cnn = new NpgsqlConnection($"Host={builder.Host};Port={builder.Port};Username={builder.Username};Password={builder.Password};Pooling=true");
cnn.Open();
using (NpgsqlCommand cmd = cnn.CreateCommand())
{
cmd.CommandText = databaseExistSql;
bool databaseExist = Convert.ToInt32(cmd.ExecuteScalar().ToString()) > 0;
if (databaseExist == false)
{
cmd.CommandText = createDatabaseSql;
cmd.ExecuteNonQuery();
}
}
return @this;
}
#endregion
#region ODBC
public static FreeSqlBuilder CreateDatabaseIfNotExists_ODBCMySql(this FreeSqlBuilder @this, string connectionString = "")
{
if (connectionString == "")
{
connectionString = GetConnectionString(@this);
}
OdbcConnectionStringBuilder builder = new OdbcConnectionStringBuilder(connectionString);
string createDatabaseSql =
$"USE mysql;CREATE DATABASE IF NOT EXISTS `{builder["DATABASE"]}` CHARACTER SET '{builder["Charset"]}' COLLATE 'utf8mb4_general_ci'";
using OdbcConnection cnn = new OdbcConnection(
$"Data Source={builder["Server"]};Port={builder["Port"]};User ID={builder["UID"]};Password={builder["PWD"]};Initial Catalog=mysql;Charset=utf8;SslMode=none;Max pool size=1");
cnn.Open();
using (OdbcCommand cmd = cnn.CreateCommand())
{
cmd.CommandText = createDatabaseSql;
cmd.ExecuteNonQuery();
}
return @this;
}
public static FreeSqlBuilder CreateDatabaseIfNotExists_ODBCSqlServer(this FreeSqlBuilder @this, string connectionString = "")
{
if (connectionString == "")
{
connectionString = GetConnectionString(@this);
}
OdbcConnectionStringBuilder builder = new OdbcConnectionStringBuilder(connectionString);
string createDatabaseSql;
if (builder.ContainsKey("AttachDBFilename") && !string.IsNullOrEmpty(builder["AttachDBFilename"].ToString()))
{
string fileName = ExpandFileName(builder["AttachDBFilename"].ToString());
string name = Path.GetFileNameWithoutExtension(fileName);
string logFileName = Path.ChangeExtension(fileName, ".ldf");
createDatabaseSql = @$"CREATE DATABASE {builder["Initial Catalog"]} on primary
(
name = '{name}',
filename = '{fileName}'
)
log on
(
name= '{name}_log',
filename = '{logFileName}'
)";
}
else
{
createDatabaseSql = @$"CREATE DATABASE {builder["Initial Catalog"]}";
}
//一个空格都不能多
//string MasterConnectionString = "Driver={SQL Server};Server=.;Initial Catalog=master;Uid=sa;Pwd=123456";
string MasterConnectionString = $"Driver={{SQL Server}};Server={builder["Server"]};Initial Catalog=master;Uid={builder["Uid"]};Pwd={builder["Pwd"]};";
using OdbcConnection cnn = new OdbcConnection(MasterConnectionString);
cnn.Open();
using OdbcCommand cmd = cnn.CreateCommand();
cmd.CommandText = $"select * from sysdatabases where name = '{builder["Initial Catalog"]}'";
OdbcDataAdapter apter = new OdbcDataAdapter(cmd);
DataSet ds = new DataSet();
apter.Fill(ds);
if (ds.Tables[0].Rows.Count == 0)
{
cmd.CommandText = createDatabaseSql;
cmd.ExecuteNonQuery();
}
return @this;
}
#endregion
}