/* 2021.10.14 */
using Apewer;
using Apewer.Source;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Net;
using System.Text;
using static Apewer.Source.OrmHelper;
#if NETFRAMEWORK
using System.Data.Sql;
#else
#endif
namespace Apewer.Source
{
///
[Serializable]
public class SqlClient : IDbClient
{
#region 变量、构造函数
private Timeout _timeout = null;
private string _connectionstring = "";
/// 获取或设置日志记录。
public Logger Logger { get; set; }
/// 超时设定。
public Timeout Timeout { get => _timeout; }
/// 使用连接字符串创建数据库连接实例。
public SqlClient(string connectionString, Timeout timeout = null)
{
_timeout = timeout ?? Timeout.Default;
_connectionstring = connectionString ?? "";
}
/// 使用连接凭据创建数据库连接实例。
public SqlClient(string address, string store, string user, string pass, Timeout timeout = null)
{
if (timeout == null) timeout = Timeout.Default;
var a = TextUtility.AntiInject(address);
var s = TextUtility.AntiInject(store);
var u = TextUtility.AntiInject(user);
var p = TextUtility.AntiInject(pass);
var cs = $"data source = {a}; initial catalog = {s}; ";
if (string.IsNullOrEmpty(u)) cs += "integrated security = sspi; ";
else
{
cs += $"user id = {u}; ";
if (!string.IsNullOrEmpty(p)) cs += $"password = {p}; ";
}
cs += $"connection timeout = {timeout.Connect}; ";
_timeout = timeout ?? Timeout.Default;
_connectionstring = cs;
}
#endregion
#region Ado - Connection
private SqlConnection _db = null;
/// 连接字符串。
public string ConnectionString { get => _connectionstring; }
/// 获取当前的 SqlConnection 对象。
public IDbConnection Connection { get => _db; }
/// 数据库是否已经连接。
public bool Online
{
get
{
if (_db == null) return false;
return (_db.State == ConnectionState.Open);
}
}
/// 连接数据库,若未连接则尝试连接,获取连接成功的状态。
public bool Connect()
{
if (_db == null)
{
_db = new SqlConnection();
_db.ConnectionString = _connectionstring;
}
else
{
if (_db.State == ConnectionState.Open) return true;
}
try
{
_db.Open();
switch (_db.State)
{
case ConnectionState.Open: return true;
default: return false;
}
}
catch (Exception ex)
{
Logger.Error(nameof(SqlClient), "Connection", ex, _db.ConnectionString);
Close();
return false;
}
}
/// 关闭连接,并释放对象所占用的系统资源。
public void Close()
{
if (_db != null)
{
if (_transaction != null)
{
if (_autocommit) Commit();
else Rollback();
}
_db.Close();
_db.Dispose();
_db = null;
}
}
/// 关闭连接,释放对象所占用的系统资源,并清除连接信息。
public void Dispose() => Close();
#endregion
#region Ado - Transaction
private IDbTransaction _transaction = null;
private bool _autocommit = false;
/// 启动事务。
public string Begin(bool commit = true) => Begin(commit, null);
/// 启动事务。
public string Begin(bool commit, Class isolation)
{
if (!Connect()) return "未连接。";
if (_transaction != null) return "存在已启动的事务,无法再次启动。";
try
{
_transaction = isolation ? _db.BeginTransaction(isolation.Value) : _db.BeginTransaction();
_autocommit = commit;
return null;
}
catch (Exception ex)
{
Logger.Error(nameof(SqlClient), "Begin", ex.Message());
return ex.Message();
}
}
/// 提交事务。
public string Commit()
{
if (_transaction == null) return "事务不存在。";
try
{
_transaction.Commit();
RuntimeUtility.Dispose(_transaction);
_transaction = null;
return null;
}
catch (Exception ex)
{
RuntimeUtility.Dispose(_transaction);
_transaction = null;
Logger.Error(nameof(SqlClient), "Commit", ex.Message());
return ex.Message();
}
}
/// 从挂起状态回滚事务。
public string Rollback()
{
if (_transaction == null) return "事务不存在。";
try
{
_transaction.Rollback();
RuntimeUtility.Dispose(_transaction);
_transaction = null;
return null;
}
catch (Exception ex)
{
RuntimeUtility.Dispose(_transaction);
_transaction = null;
Logger.Error(nameof(SqlClient), "Rollback", ex.Message);
return ex.Message();
}
}
#endregion
#region Ado - SQL
/// 查询。
public IQuery Query(string sql) => Query(sql, null);
/// 查询。
public IQuery Query(string sql, IEnumerable parameters)
{
if (TextUtility.IsBlank(sql)) return Example.InvalidQueryStatement;
var connected = Connect();
if (!connected) return Example.InvalidQueryConnection;
try
{
using (var command = new SqlCommand())
{
command.Connection = _db;
command.CommandTimeout = _timeout.Query;
command.CommandText = sql;
if (parameters != null)
{
foreach (var parameter in parameters)
{
if (parameter != null) command.Parameters.Add(parameter);
}
}
using (var ds = new DataSet())
{
using (var da = new SqlDataAdapter(sql, _db))
{
const string name = "resule";
da.Fill(ds, name);
var table = ds.Tables[name];
return new Query(table, true);
}
}
}
}
catch (Exception exception)
{
Logger.Error(nameof(SqlClient), "Query", exception, sql);
return new Query(exception);
}
}
/// 执行。
public IExecute Execute(string sql) => Execute(sql, null);
/// 执行单条 Transact-SQL 语句,并加入参数。
public IExecute Execute(string sql, IEnumerable parameters)
{
if (TextUtility.IsBlank(sql)) return Example.InvalidExecuteStatement;
var connected = Connect();
if (!connected) return Example.InvalidExecuteConnection;
var inTransaction = _transaction != null;
if (!inTransaction) Begin();
try
{
using (var command = new SqlCommand())
{
command.Connection = _db;
command.Transaction = (SqlTransaction)_transaction;
command.CommandTimeout = _timeout.Execute;
command.CommandText = sql;
if (parameters != null)
{
foreach (var parameter in parameters)
{
if (parameter != null) command.Parameters.Add(parameter);
}
}
var rows = command.ExecuteNonQuery();
if (!inTransaction) Commit(); // todo 此处应该检查事务提交产生的错误。
return new Execute(true, rows);
}
}
catch (Exception exception)
{
Logger.Error(nameof(SqlClient), "Execute", exception, sql);
if (!inTransaction) Rollback();
return new Execute(exception);
}
}
#endregion
#region ORM
/// 查询数据库中的所有表名。
public string[] TableNames()
{
var list = new List();
if (Connect())
{
var sql = "select [name] from [sysobjects] where [type] = 'u' order by [name]; ";
var query = (Query)Query(sql);
for (int r = 0; r < query.Rows; r++)
{
var cell = query.Text(r, 0);
if (TextUtility.IsBlank(cell)) continue;
list.Add(cell);
}
query.Dispose();
}
return list.ToArray();
}
/// 查询数据库实例中的所有数据库名。
public string[] StoreNames()
{
var list = new List();
if (Connect())
{
var sql = "select [name] from [master]..[sysdatabases] order by [name]; ";
var query = (Query)Query(sql);
for (int r = 0; r < query.Rows; r++)
{
var cell = query.Text(r, 0);
if (TextUtility.IsBlank(cell)) continue;
if (cell == "master") continue;
if (cell == "model") continue;
if (cell == "msdb") continue;
if (cell == "tempdb") continue;
list.Add(cell);
}
query.Dispose();
}
return list.ToArray();
}
/// 查询表中的所有列名。
public string[] ColumnNames(string tableName)
{
var list = new List();
if (Connect())
{
var table = TextUtility.AntiInject(tableName);
var sql = TextUtility.Merge("select [name] from [syscolumns] where [id] = object_id('", table, "'); ");
var query = (Query)Query(sql);
for (int r = 0; r < query.Rows; r++)
{
var cell = query.Text(r, 0);
if (TextUtility.IsBlank(cell)) continue;
list.Add(cell);
}
query.Dispose();
}
return list.ToArray();
}
/// 创建表,当表不存在时创建表,当现存表中缺少模型中属性对应的列时增加列。成功时返回空字符串,发生异常时返回异常信息。
public string Initialize() where T : class, new() => Initialize(typeof(T));
/// 创建表,当表不存在时创建表,当现存表中缺少模型中属性对应的列时增加列。成功时返回空字符串,发生异常时返回异常信息。
public string Initialize(Type model)
{
var structure = TableStructure.Parse(model);
if (structure == null) return "无法解析记录模型。";
// 连接数据库。
if (!Connect()) return "连接数据库失败。";
// 检查现存表。
var exists = false;
var tables = TableNames();
if (tables.Length > 0)
{
var lower = structure.Name.ToLower();
foreach (var table in tables)
{
if (TextUtility.IsBlank(table)) continue;
if (table.ToLower() == lower)
{
exists = true;
break;
}
}
}
if (exists)
{
// 获取已存在的列名。
var columns = ColumnNames(structure.Name);
if (columns.Length > 0)
{
var lower = new List();
foreach (var column in columns)
{
if (TextUtility.IsBlank(column)) continue;
lower.Add(column.ToLower());
}
columns = lower.ToArray();
}
// 增加列。
foreach (var column in structure.Columns)
{
// 检查 Independent 特性。
if (structure.Independent && column.Independent) continue;
// 去重。
var lower = column.Field.ToLower();
if (columns.Contains(lower)) continue;
var type = GetColumnDeclaration(column);
if (type == TextUtility.Empty) return TextUtility.Merge("类型 ", column.Type.ToString(), " 不受支持。");
var sql = TextUtility.Merge("alter table [", structure.Name, "] add ", type, "; ");
var execute = Execute(sql);
if (execute.Success == false) return execute.Message;
}
return TextUtility.Empty;
}
else
{
var sqlcolumns = new List();
foreach (var column in structure.Columns)
{
// 检查 Independent 特性。
if (structure.Independent && column.Independent) continue;
var type = GetColumnDeclaration(column);
if (!column.Independent && column.Property.Name == "Key") type = type + " primary key";
if (type == TextUtility.Empty) return TextUtility.Merge("类型 ", column.Type.ToString(), " 不受支持。");
sqlcolumns.Add(type);
}
var sql = TextUtility.Merge("create table [", structure.Name, "](", string.Join(", ", sqlcolumns.ToArray()), "); ");
var execute = Execute(sql);
if (execute.Success) return TextUtility.Empty;
return execute.Message;
}
}
/// 插入记录。返回错误信息。
public string Insert(object record)
{
if (record == null) return "参数无效。";
FixProperties(record);
var structure = TableStructure.Parse(record.GetType());
if (structure == null) return "无法解析记录模型。";
var parameters = structure.CreateParameters(record, CreateDataParameter);
var sql = GenerateInsertStatement(structure.Name, parameters);
var execute = Execute(sql, parameters);
if (execute.Success) return TextUtility.Empty;
return execute.Message;
}
/// 更新记录,实体中的 Key 属性不被更新。返回错误信息。
/// 无法更新带有 Independent 特性的模型(缺少 Key 属性)。
public string Update(IRecord record)
{
if (record == null) return "参数无效。";
FixProperties(record);
SetUpdated(record);
var structure = TableStructure.Parse(record.GetType());
if (structure == null) return "无法解析记录模型。";
if (structure.Independent) return "无法更新带有 Independent 特性的模型。";
var parameters = structure.CreateParameters(record, CreateDataParameter, "_key");
var sql = GenerateUpdateStatement(structure.Name, record.Key, parameters);
var execute = Execute(sql, parameters);
if (execute.Success) return TextUtility.Empty;
return execute.Message;
}
/// 获取按指定语句查询到的所有记录。
public Result