mirror of
https://github.com/nsnail/FreeSql.git
synced 2025-06-18 20:08:15 +08:00
拆分 FreeSql 按需引用
This commit is contained in:
88
Providers/FreeSql.Provider.SqlServer/Curd/SqlServerDelete.cs
Normal file
88
Providers/FreeSql.Provider.SqlServer/Curd/SqlServerDelete.cs
Normal file
@ -0,0 +1,88 @@
|
||||
using FreeSql.Internal;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace FreeSql.SqlServer.Curd {
|
||||
|
||||
class SqlServerDelete<T1> : Internal.CommonProvider.DeleteProvider<T1> where T1 : class {
|
||||
public SqlServerDelete(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere)
|
||||
: base(orm, commonUtils, commonExpression, dywhere) {
|
||||
}
|
||||
|
||||
public override List<T1> ExecuteDeleted() {
|
||||
var sql = this.ToSql();
|
||||
if (string.IsNullOrEmpty(sql)) return new List<T1>();
|
||||
|
||||
var sb = new StringBuilder();
|
||||
sb.Append(" OUTPUT ");
|
||||
var colidx = 0;
|
||||
foreach (var col in _table.Columns.Values) {
|
||||
if (colidx > 0) sb.Append(", ");
|
||||
sb.Append("DELETED.").Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName));
|
||||
++colidx;
|
||||
}
|
||||
|
||||
var validx = sql.IndexOf(" WHERE ");
|
||||
if (validx == -1) throw new ArgumentException("找不到 WHERE ");
|
||||
sb.Insert(0, sql.Substring(0, validx));
|
||||
sb.Append(sql.Substring(validx));
|
||||
|
||||
sql = sb.ToString();
|
||||
var dbParms = _params.ToArray();
|
||||
var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Delete, sql, dbParms);
|
||||
_orm.Aop.CurdBefore?.Invoke(this, before);
|
||||
var ret = new List<T1>();
|
||||
Exception exception = null;
|
||||
try {
|
||||
ret = _orm.Ado.Query<T1>(_connection, _transaction, CommandType.Text, sql, dbParms);
|
||||
} catch (Exception ex) {
|
||||
exception = ex;
|
||||
throw ex;
|
||||
} finally {
|
||||
var after = new Aop.CurdAfterEventArgs(before, exception, ret);
|
||||
_orm.Aop.CurdAfter?.Invoke(this, after);
|
||||
}
|
||||
this.ClearData();
|
||||
return ret;
|
||||
}
|
||||
async public override Task<List<T1>> ExecuteDeletedAsync() {
|
||||
var sql = this.ToSql();
|
||||
if (string.IsNullOrEmpty(sql)) return new List<T1>();
|
||||
|
||||
var sb = new StringBuilder();
|
||||
sb.Append(" OUTPUT ");
|
||||
var colidx = 0;
|
||||
foreach (var col in _table.Columns.Values) {
|
||||
if (colidx > 0) sb.Append(", ");
|
||||
sb.Append("DELETED.").Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName));
|
||||
++colidx;
|
||||
}
|
||||
|
||||
var validx = sql.IndexOf(" WHERE ");
|
||||
if (validx == -1) throw new ArgumentException("找不到 WHERE ");
|
||||
sb.Insert(0, sql.Substring(0, validx));
|
||||
sb.Append(sql.Substring(validx));
|
||||
|
||||
sql = sb.ToString();
|
||||
var dbParms = _params.ToArray();
|
||||
var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Delete, sql, dbParms);
|
||||
_orm.Aop.CurdBefore?.Invoke(this, before);
|
||||
var ret = new List<T1>();
|
||||
Exception exception = null;
|
||||
try {
|
||||
ret = await _orm.Ado.QueryAsync<T1>(_connection, _transaction, CommandType.Text, sql, dbParms);
|
||||
} catch (Exception ex) {
|
||||
exception = ex;
|
||||
throw ex;
|
||||
} finally {
|
||||
var after = new Aop.CurdAfterEventArgs(before, exception, ret);
|
||||
_orm.Aop.CurdAfter?.Invoke(this, after);
|
||||
}
|
||||
this.ClearData();
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
}
|
139
Providers/FreeSql.Provider.SqlServer/Curd/SqlServerInsert.cs
Normal file
139
Providers/FreeSql.Provider.SqlServer/Curd/SqlServerInsert.cs
Normal file
@ -0,0 +1,139 @@
|
||||
using FreeSql.Internal;
|
||||
using SafeObjectPool;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace FreeSql.SqlServer.Curd {
|
||||
|
||||
class SqlServerInsert<T1> : Internal.CommonProvider.InsertProvider<T1> where T1 : class {
|
||||
public SqlServerInsert(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression)
|
||||
: base(orm, commonUtils, commonExpression) {
|
||||
}
|
||||
|
||||
public override int ExecuteAffrows() => base.SplitExecuteAffrows(1000, 2100);
|
||||
public override Task<int> ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(1000, 2100);
|
||||
public override long ExecuteIdentity() => base.SplitExecuteIdentity(1000, 2100);
|
||||
public override Task<long> ExecuteIdentityAsync() => base.SplitExecuteIdentityAsync(1000, 2100);
|
||||
public override List<T1> ExecuteInserted() => base.SplitExecuteInserted(1000, 2100);
|
||||
public override Task<List<T1>> ExecuteInsertedAsync() => base.SplitExecuteInsertedAsync(1000, 2100);
|
||||
|
||||
|
||||
protected override long RawExecuteIdentity() {
|
||||
var sql = this.ToSql();
|
||||
if (string.IsNullOrEmpty(sql)) return 0;
|
||||
|
||||
sql = string.Concat(sql, "; SELECT SCOPE_IDENTITY();");
|
||||
var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params);
|
||||
_orm.Aop.CurdBefore?.Invoke(this, before);
|
||||
long ret = 0;
|
||||
Exception exception = null;
|
||||
try {
|
||||
long.TryParse(string.Concat(_orm.Ado.ExecuteScalar(_connection, _transaction, CommandType.Text, sql, _params)), out ret);
|
||||
} catch (Exception ex) {
|
||||
exception = ex;
|
||||
throw ex;
|
||||
} finally {
|
||||
var after = new Aop.CurdAfterEventArgs(before, exception, ret);
|
||||
_orm.Aop.CurdAfter?.Invoke(this, after);
|
||||
}
|
||||
this.ClearData();
|
||||
return ret;
|
||||
}
|
||||
async protected override Task<long> RawExecuteIdentityAsync() {
|
||||
var sql = this.ToSql();
|
||||
if (string.IsNullOrEmpty(sql)) return 0;
|
||||
|
||||
sql = string.Concat(sql, "; SELECT SCOPE_IDENTITY();");
|
||||
var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params);
|
||||
_orm.Aop.CurdBefore?.Invoke(this, before);
|
||||
long ret = 0;
|
||||
Exception exception = null;
|
||||
try {
|
||||
long.TryParse(string.Concat(await _orm.Ado.ExecuteScalarAsync(_connection, _transaction, CommandType.Text, sql, _params)), out ret);
|
||||
} catch (Exception ex) {
|
||||
exception = ex;
|
||||
throw ex;
|
||||
} finally {
|
||||
var after = new Aop.CurdAfterEventArgs(before, exception, ret);
|
||||
_orm.Aop.CurdAfter?.Invoke(this, after);
|
||||
}
|
||||
this.ClearData();
|
||||
return ret;
|
||||
}
|
||||
|
||||
protected override List<T1> RawExecuteInserted() {
|
||||
var sql = this.ToSql();
|
||||
if (string.IsNullOrEmpty(sql)) return new List<T1>();
|
||||
|
||||
var sb = new StringBuilder();
|
||||
sb.Append(" OUTPUT ");
|
||||
var colidx = 0;
|
||||
foreach (var col in _table.Columns.Values) {
|
||||
if (colidx > 0) sb.Append(", ");
|
||||
sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, $"INSERTED.{_commonUtils.QuoteSqlName(col.Attribute.Name)}")).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName));
|
||||
++colidx;
|
||||
}
|
||||
|
||||
var validx = sql.IndexOf(") VALUES");
|
||||
if (validx == -1) throw new ArgumentException("找不到 VALUES");
|
||||
sb.Insert(0, sql.Substring(0, validx + 1));
|
||||
sb.Append(sql.Substring(validx + 1));
|
||||
|
||||
sql = sb.ToString();
|
||||
var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params);
|
||||
_orm.Aop.CurdBefore?.Invoke(this, before);
|
||||
var ret = new List<T1>();
|
||||
Exception exception = null;
|
||||
try {
|
||||
ret = _orm.Ado.Query<T1>(_connection, _transaction, CommandType.Text, sql, _params);
|
||||
} catch (Exception ex) {
|
||||
exception = ex;
|
||||
throw ex;
|
||||
} finally {
|
||||
var after = new Aop.CurdAfterEventArgs(before, exception, ret);
|
||||
_orm.Aop.CurdAfter?.Invoke(this, after);
|
||||
}
|
||||
this.ClearData();
|
||||
return ret;
|
||||
}
|
||||
async protected override Task<List<T1>> RawExecuteInsertedAsync() {
|
||||
var sql = this.ToSql();
|
||||
if (string.IsNullOrEmpty(sql)) return new List<T1>();
|
||||
|
||||
var sb = new StringBuilder();
|
||||
sb.Append(" OUTPUT ");
|
||||
var colidx = 0;
|
||||
foreach (var col in _table.Columns.Values) {
|
||||
if (colidx > 0) sb.Append(", ");
|
||||
sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, $"INSERTED.{_commonUtils.QuoteSqlName(col.Attribute.Name)}")).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName));
|
||||
++colidx;
|
||||
}
|
||||
|
||||
var validx = sql.IndexOf(") VALUES");
|
||||
if (validx == -1) throw new ArgumentException("找不到 VALUES");
|
||||
sb.Insert(0, sql.Substring(0, validx + 1));
|
||||
sb.Append(sql.Substring(validx + 1));
|
||||
|
||||
sql = sb.ToString();
|
||||
var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params);
|
||||
_orm.Aop.CurdBefore?.Invoke(this, before);
|
||||
var ret = new List<T1>();
|
||||
Exception exception = null;
|
||||
try {
|
||||
ret = await _orm.Ado.QueryAsync<T1>(_connection, _transaction, CommandType.Text, sql, _params);
|
||||
} catch (Exception ex) {
|
||||
exception = ex;
|
||||
throw ex;
|
||||
} finally {
|
||||
var after = new Aop.CurdAfterEventArgs(before, exception, ret);
|
||||
_orm.Aop.CurdAfter?.Invoke(this, after);
|
||||
}
|
||||
this.ClearData();
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
}
|
225
Providers/FreeSql.Provider.SqlServer/Curd/SqlServerSelect.cs
Normal file
225
Providers/FreeSql.Provider.SqlServer/Curd/SqlServerSelect.cs
Normal file
@ -0,0 +1,225 @@
|
||||
using FreeSql.Internal;
|
||||
using FreeSql.Internal.Model;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Text;
|
||||
|
||||
namespace FreeSql.SqlServer.Curd {
|
||||
|
||||
class SqlServerSelect<T1> : FreeSql.Internal.CommonProvider.Select1Provider<T1> where T1 : class {
|
||||
|
||||
internal static string ToSqlStatic(CommonUtils _commonUtils, string _select, bool _distinct, string field, StringBuilder _join, StringBuilder _where, string _groupby, string _having, string _orderby, int _skip, int _limit, List<SelectTableInfo> _tables, Func<Type, string, string> tableRuleInvoke, IFreeSql _orm)
|
||||
=> (_commonUtils as SqlServerUtils).IsSelectRowNumber ?
|
||||
ToSqlStaticRowNumber(_commonUtils, _select, _distinct, field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, tableRuleInvoke, _orm) :
|
||||
ToSqlStaticOffsetFetchNext(_commonUtils, _select, _distinct, field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, tableRuleInvoke, _orm);
|
||||
|
||||
#region SqlServer 2005 row_number
|
||||
internal static string ToSqlStaticRowNumber(CommonUtils _commonUtils, string _select, bool _distinct, string field, StringBuilder _join, StringBuilder _where, string _groupby, string _having, string _orderby, int _skip, int _limit, List<SelectTableInfo> _tables, Func<Type, string, string> tableRuleInvoke, IFreeSql _orm) {
|
||||
if (_orm.CodeFirst.IsAutoSyncStructure)
|
||||
_orm.CodeFirst.SyncStructure(_tables.Select(a => a.Table.Type).ToArray());
|
||||
|
||||
var sb = new StringBuilder();
|
||||
var sbnav = new StringBuilder();
|
||||
sb.Append(_select);
|
||||
if (_distinct) sb.Append("DISTINCT ");
|
||||
if (_limit > 0) sb.Append("TOP ").Append(_skip + _limit).Append(" ");
|
||||
sb.Append(field);
|
||||
if (_skip > 0) {
|
||||
if (string.IsNullOrEmpty(_orderby)) {
|
||||
var pktb = _tables.Where(a => a.Table.Primarys.Any()).FirstOrDefault();
|
||||
if (pktb != null) _orderby = string.Concat(" \r\nORDER BY ", pktb.Alias, ".", _commonUtils.QuoteSqlName(pktb?.Table.Primarys.First().Attribute.Name));
|
||||
else _orderby = string.Concat(" \r\nORDER BY ", _tables.First().Alias, ".", _commonUtils.QuoteSqlName(_tables.First().Table.Columns.First().Value.Attribute.Name));
|
||||
}
|
||||
sb.Append(", ROW_NUMBER() OVER(").Append(_orderby).Append(") AS __rownum__");
|
||||
}
|
||||
sb.Append(" \r\nFROM ");
|
||||
var tbsjoin = _tables.Where(a => a.Type != SelectTableInfoType.From).ToArray();
|
||||
var tbsfrom = _tables.Where(a => a.Type == SelectTableInfoType.From).ToArray();
|
||||
for (var a = 0; a < tbsfrom.Length; a++) {
|
||||
sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[a].Table.Type, tbsfrom[a].Table.DbName))).Append(" ").Append(tbsfrom[a].Alias);
|
||||
if (tbsjoin.Length > 0) {
|
||||
//如果存在 join 查询,则处理 from t1, t2 改为 from t1 inner join t2 on 1 = 1
|
||||
for (var b = 1; b < tbsfrom.Length; b++) {
|
||||
sb.Append(" \r\nLEFT JOIN ").Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[b].Table.Type, tbsfrom[b].Table.DbName))).Append(" ").Append(tbsfrom[b].Alias);
|
||||
if (string.IsNullOrEmpty(tbsfrom[b].NavigateCondition) && string.IsNullOrEmpty(tbsfrom[b].On)) sb.Append(" ON 1 = 1");
|
||||
else sb.Append(" ON ").Append(tbsfrom[b].NavigateCondition ?? tbsfrom[b].On);
|
||||
}
|
||||
break;
|
||||
} else {
|
||||
if (!string.IsNullOrEmpty(tbsfrom[a].NavigateCondition)) sbnav.Append(" AND (").Append(tbsfrom[a].NavigateCondition).Append(")");
|
||||
if (!string.IsNullOrEmpty(tbsfrom[a].On)) sbnav.Append(" AND (").Append(tbsfrom[a].On).Append(")");
|
||||
}
|
||||
if (a < tbsfrom.Length - 1) sb.Append(", ");
|
||||
}
|
||||
foreach (var tb in tbsjoin) {
|
||||
if (tb.Type == SelectTableInfoType.Parent) continue;
|
||||
switch (tb.Type) {
|
||||
case SelectTableInfoType.LeftJoin:
|
||||
sb.Append(" \r\nLEFT JOIN ");
|
||||
break;
|
||||
case SelectTableInfoType.InnerJoin:
|
||||
sb.Append(" \r\nINNER JOIN ");
|
||||
break;
|
||||
case SelectTableInfoType.RightJoin:
|
||||
sb.Append(" \r\nRIGHT JOIN ");
|
||||
break;
|
||||
}
|
||||
sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tb.Table.Type, tb.Table.DbName))).Append(" ").Append(tb.Alias).Append(" ON ").Append(tb.On ?? tb.NavigateCondition);
|
||||
if (!string.IsNullOrEmpty(tb.On) && !string.IsNullOrEmpty(tb.NavigateCondition)) sbnav.Append(" AND (").Append(tb.NavigateCondition).Append(")");
|
||||
}
|
||||
if (_join.Length > 0) sb.Append(_join);
|
||||
|
||||
sbnav.Append(_where);
|
||||
foreach (var tb in _tables) {
|
||||
if (tb.Type == SelectTableInfoType.Parent) continue;
|
||||
if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false)
|
||||
sbnav.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")");
|
||||
}
|
||||
if (sbnav.Length > 0) {
|
||||
sb.Append(" \r\nWHERE ").Append(sbnav.Remove(0, 5));
|
||||
}
|
||||
if (string.IsNullOrEmpty(_groupby) == false) {
|
||||
sb.Append(_groupby);
|
||||
if (string.IsNullOrEmpty(_having) == false)
|
||||
sb.Append(" \r\nHAVING ").Append(_having.Substring(5));
|
||||
}
|
||||
if (_skip <= 0)
|
||||
sb.Append(_orderby);
|
||||
else
|
||||
sb.Insert(0, "WITH t AS ( ").Append(" ) SELECT t.* FROM t where __rownum__ > ").Append(_skip);
|
||||
|
||||
sbnav.Clear();
|
||||
return sb.ToString();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region SqlServer 2012+ offset feach next
|
||||
internal static string ToSqlStaticOffsetFetchNext(CommonUtils _commonUtils, string _select, bool _distinct, string field, StringBuilder _join, StringBuilder _where, string _groupby, string _having, string _orderby, int _skip, int _limit, List<SelectTableInfo> _tables, Func<Type, string, string> tableRuleInvoke, IFreeSql _orm) {
|
||||
if (_orm.CodeFirst.IsAutoSyncStructure)
|
||||
_orm.CodeFirst.SyncStructure(_tables.Select(a => a.Table.Type).ToArray());
|
||||
|
||||
var sb = new StringBuilder();
|
||||
var sbnav = new StringBuilder();
|
||||
sb.Append(_select);
|
||||
if (_distinct) sb.Append("DISTINCT ");
|
||||
if (_skip <= 0 && _limit > 0) sb.Append("TOP ").Append(_limit).Append(" ");
|
||||
sb.Append(field);
|
||||
sb.Append(" \r\nFROM ");
|
||||
var tbsjoin = _tables.Where(a => a.Type != SelectTableInfoType.From).ToArray();
|
||||
var tbsfrom = _tables.Where(a => a.Type == SelectTableInfoType.From).ToArray();
|
||||
for (var a = 0; a < tbsfrom.Length; a++) {
|
||||
sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[a].Table.Type, tbsfrom[a].Table.DbName))).Append(" ").Append(tbsfrom[a].Alias);
|
||||
if (tbsjoin.Length > 0) {
|
||||
//如果存在 join 查询,则处理 from t1, t2 改为 from t1 inner join t2 on 1 = 1
|
||||
for (var b = 1; b < tbsfrom.Length; b++) {
|
||||
sb.Append(" \r\nLEFT JOIN ").Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[b].Table.Type, tbsfrom[b].Table.DbName))).Append(" ").Append(tbsfrom[b].Alias);
|
||||
if (string.IsNullOrEmpty(tbsfrom[b].NavigateCondition) && string.IsNullOrEmpty(tbsfrom[b].On)) sb.Append(" ON 1 = 1");
|
||||
else sb.Append(" ON ").Append(tbsfrom[b].NavigateCondition ?? tbsfrom[b].On);
|
||||
}
|
||||
break;
|
||||
} else {
|
||||
if (!string.IsNullOrEmpty(tbsfrom[a].NavigateCondition)) sbnav.Append(" AND (").Append(tbsfrom[a].NavigateCondition).Append(")");
|
||||
if (!string.IsNullOrEmpty(tbsfrom[a].On)) sbnav.Append(" AND (").Append(tbsfrom[a].On).Append(")");
|
||||
}
|
||||
if (a < tbsfrom.Length - 1) sb.Append(", ");
|
||||
}
|
||||
foreach (var tb in tbsjoin) {
|
||||
if (tb.Type == SelectTableInfoType.Parent) continue;
|
||||
switch (tb.Type) {
|
||||
case SelectTableInfoType.LeftJoin:
|
||||
sb.Append(" \r\nLEFT JOIN ");
|
||||
break;
|
||||
case SelectTableInfoType.InnerJoin:
|
||||
sb.Append(" \r\nINNER JOIN ");
|
||||
break;
|
||||
case SelectTableInfoType.RightJoin:
|
||||
sb.Append(" \r\nRIGHT JOIN ");
|
||||
break;
|
||||
}
|
||||
sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tb.Table.Type, tb.Table.DbName))).Append(" ").Append(tb.Alias).Append(" ON ").Append(tb.On ?? tb.NavigateCondition);
|
||||
if (!string.IsNullOrEmpty(tb.On) && !string.IsNullOrEmpty(tb.NavigateCondition)) sbnav.Append(" AND (").Append(tb.NavigateCondition).Append(")");
|
||||
}
|
||||
if (_join.Length > 0) sb.Append(_join);
|
||||
|
||||
sbnav.Append(_where);
|
||||
foreach (var tb in _tables) {
|
||||
if (tb.Type == SelectTableInfoType.Parent) continue;
|
||||
if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false)
|
||||
sbnav.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")");
|
||||
}
|
||||
if (sbnav.Length > 0) {
|
||||
sb.Append(" \r\nWHERE ").Append(sbnav.Remove(0, 5));
|
||||
}
|
||||
if (string.IsNullOrEmpty(_groupby) == false) {
|
||||
sb.Append(_groupby);
|
||||
if (string.IsNullOrEmpty(_having) == false)
|
||||
sb.Append(" \r\nHAVING ").Append(_having.Substring(5));
|
||||
}
|
||||
if (_skip > 0) {
|
||||
if (string.IsNullOrEmpty(_orderby)) {
|
||||
var pktb = _tables.Where(a => a.Table.Primarys.Any()).FirstOrDefault();
|
||||
if (pktb != null) _orderby = string.Concat(" \r\nORDER BY ", pktb.Alias, ".", _commonUtils.QuoteSqlName(pktb?.Table.Primarys.First().Attribute.Name));
|
||||
else _orderby = string.Concat(" \r\nORDER BY ", _tables.First().Alias, ".", _commonUtils.QuoteSqlName(_tables.First().Table.Columns.First().Value.Attribute.Name));
|
||||
}
|
||||
sb.Append(_orderby).Append($" \r\nOFFSET {_skip} ROW");
|
||||
if (_limit > 0) sb.Append($" \r\nFETCH NEXT {_limit} ROW ONLY");
|
||||
} else {
|
||||
sb.Append(_orderby);
|
||||
}
|
||||
|
||||
sbnav.Clear();
|
||||
return sb.ToString();
|
||||
}
|
||||
#endregion
|
||||
|
||||
public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { }
|
||||
public override ISelect<T1, T2> From<T2>(Expression<Func<ISelectFromExpression<T1>, T2, ISelectFromExpression<T1>>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect<T1, T2>(_orm, _commonUtils, _commonExpression, null); SqlServerSelect<T1>.CopyData(this, ret, exp?.Parameters); return ret; }
|
||||
public override ISelect<T1, T2, T3> From<T2, T3>(Expression<Func<ISelectFromExpression<T1>, T2, T3, ISelectFromExpression<T1>>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect<T1, T2, T3>(_orm, _commonUtils, _commonExpression, null); SqlServerSelect<T1>.CopyData(this, ret, exp?.Parameters); return ret; }
|
||||
public override ISelect<T1, T2, T3, T4> From<T2, T3, T4>(Expression<Func<ISelectFromExpression<T1>, T2, T3, T4, ISelectFromExpression<T1>>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect<T1, T2, T3, T4>(_orm, _commonUtils, _commonExpression, null); SqlServerSelect<T1>.CopyData(this, ret, exp?.Parameters); return ret; }
|
||||
public override ISelect<T1, T2, T3, T4, T5> From<T2, T3, T4, T5>(Expression<Func<ISelectFromExpression<T1>, T2, T3, T4, T5, ISelectFromExpression<T1>>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect<T1, T2, T3, T4, T5>(_orm, _commonUtils, _commonExpression, null); SqlServerSelect<T1>.CopyData(this, ret, exp?.Parameters); return ret; }
|
||||
public override ISelect<T1, T2, T3, T4, T5, T6> From<T2, T3, T4, T5, T6>(Expression<Func<ISelectFromExpression<T1>, T2, T3, T4, T5, T6, ISelectFromExpression<T1>>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect<T1, T2, T3, T4, T5, T6>(_orm, _commonUtils, _commonExpression, null); SqlServerSelect<T1>.CopyData(this, ret, exp?.Parameters); return ret; }
|
||||
public override ISelect<T1, T2, T3, T4, T5, T6, T7> From<T2, T3, T4, T5, T6, T7>(Expression<Func<ISelectFromExpression<T1>, T2, T3, T4, T5, T6, T7, ISelectFromExpression<T1>>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect<T1, T2, T3, T4, T5, T6, T7>(_orm, _commonUtils, _commonExpression, null); SqlServerSelect<T1>.CopyData(this, ret, exp?.Parameters); return ret; }
|
||||
public override ISelect<T1, T2, T3, T4, T5, T6, T7, T8> From<T2, T3, T4, T5, T6, T7, T8>(Expression<Func<ISelectFromExpression<T1>, T2, T3, T4, T5, T6, T7, T8, ISelectFromExpression<T1>>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect<T1, T2, T3, T4, T5, T6, T7, T8>(_orm, _commonUtils, _commonExpression, null); SqlServerSelect<T1>.CopyData(this, ret, exp?.Parameters); return ret; }
|
||||
public override ISelect<T1, T2, T3, T4, T5, T6, T7, T8, T9> From<T2, T3, T4, T5, T6, T7, T8, T9>(Expression<Func<ISelectFromExpression<T1>, T2, T3, T4, T5, T6, T7, T8, T9, ISelectFromExpression<T1>>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect<T1, T2, T3, T4, T5, T6, T7, T8, T9>(_orm, _commonUtils, _commonExpression, null); SqlServerSelect<T1>.CopyData(this, ret, exp?.Parameters); return ret; }
|
||||
public override ISelect<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> From<T2, T3, T4, T5, T6, T7, T8, T9, T10>(Expression<Func<ISelectFromExpression<T1>, T2, T3, T4, T5, T6, T7, T8, T9, T10, ISelectFromExpression<T1>>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(_orm, _commonUtils, _commonExpression, null); SqlServerSelect<T1>.CopyData(this, ret, exp?.Parameters); return ret; }
|
||||
public override string ToSql(string field = null) => ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm);
|
||||
}
|
||||
class SqlServerSelect<T1, T2> : FreeSql.Internal.CommonProvider.Select2Provider<T1, T2> where T1 : class where T2 : class {
|
||||
public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { }
|
||||
public override string ToSql(string field = null) => SqlServerSelect<T1>.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm);
|
||||
}
|
||||
class SqlServerSelect<T1, T2, T3> : FreeSql.Internal.CommonProvider.Select3Provider<T1, T2, T3> where T1 : class where T2 : class where T3 : class {
|
||||
public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { }
|
||||
public override string ToSql(string field = null) => SqlServerSelect<T1>.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm);
|
||||
}
|
||||
class SqlServerSelect<T1, T2, T3, T4> : FreeSql.Internal.CommonProvider.Select4Provider<T1, T2, T3, T4> where T1 : class where T2 : class where T3 : class where T4 : class {
|
||||
public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { }
|
||||
public override string ToSql(string field = null) => SqlServerSelect<T1>.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm);
|
||||
}
|
||||
class SqlServerSelect<T1, T2, T3, T4, T5> : FreeSql.Internal.CommonProvider.Select5Provider<T1, T2, T3, T4, T5> where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class {
|
||||
public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { }
|
||||
public override string ToSql(string field = null) => SqlServerSelect<T1>.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm);
|
||||
}
|
||||
class SqlServerSelect<T1, T2, T3, T4, T5, T6> : FreeSql.Internal.CommonProvider.Select6Provider<T1, T2, T3, T4, T5, T6> where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class {
|
||||
public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { }
|
||||
public override string ToSql(string field = null) => SqlServerSelect<T1>.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm);
|
||||
}
|
||||
class SqlServerSelect<T1, T2, T3, T4, T5, T6, T7> : FreeSql.Internal.CommonProvider.Select7Provider<T1, T2, T3, T4, T5, T6, T7> where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class {
|
||||
public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { }
|
||||
public override string ToSql(string field = null) => SqlServerSelect<T1>.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm);
|
||||
}
|
||||
class SqlServerSelect<T1, T2, T3, T4, T5, T6, T7, T8> : FreeSql.Internal.CommonProvider.Select8Provider<T1, T2, T3, T4, T5, T6, T7, T8> where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class {
|
||||
public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { }
|
||||
public override string ToSql(string field = null) => SqlServerSelect<T1>.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm);
|
||||
}
|
||||
class SqlServerSelect<T1, T2, T3, T4, T5, T6, T7, T8, T9> : FreeSql.Internal.CommonProvider.Select9Provider<T1, T2, T3, T4, T5, T6, T7, T8, T9> where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class {
|
||||
public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { }
|
||||
public override string ToSql(string field = null) => SqlServerSelect<T1>.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm);
|
||||
}
|
||||
class SqlServerSelect<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> : FreeSql.Internal.CommonProvider.Select10Provider<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class {
|
||||
public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { }
|
||||
public override string ToSql(string field = null) => SqlServerSelect<T1>.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm);
|
||||
}
|
||||
}
|
127
Providers/FreeSql.Provider.SqlServer/Curd/SqlServerUpdate.cs
Normal file
127
Providers/FreeSql.Provider.SqlServer/Curd/SqlServerUpdate.cs
Normal file
@ -0,0 +1,127 @@
|
||||
using FreeSql.Internal;
|
||||
using FreeSql.Internal.Model;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace FreeSql.SqlServer.Curd {
|
||||
|
||||
class SqlServerUpdate<T1> : Internal.CommonProvider.UpdateProvider<T1> where T1 : class {
|
||||
|
||||
public SqlServerUpdate(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere)
|
||||
: base(orm, commonUtils, commonExpression, dywhere) {
|
||||
}
|
||||
|
||||
public override int ExecuteAffrows() => base.SplitExecuteAffrows(500, 2100);
|
||||
public override Task<int> ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(500, 2100);
|
||||
public override List<T1> ExecuteUpdated() => base.SplitExecuteUpdated(500, 2100);
|
||||
public override Task<List<T1>> ExecuteUpdatedAsync() => base.SplitExecuteUpdatedAsync(500, 2100);
|
||||
|
||||
|
||||
protected override List<T1> RawExecuteUpdated() {
|
||||
var sql = this.ToSql();
|
||||
if (string.IsNullOrEmpty(sql)) return new List<T1>();
|
||||
|
||||
var sb = new StringBuilder();
|
||||
sb.Append(" OUTPUT ");
|
||||
var colidx = 0;
|
||||
foreach (var col in _table.Columns.Values) {
|
||||
if (colidx > 0) sb.Append(", ");
|
||||
sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, $"INSERTED.{_commonUtils.QuoteSqlName(col.Attribute.Name)}")).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName));
|
||||
++colidx;
|
||||
}
|
||||
|
||||
var validx = sql.IndexOf(" WHERE ");
|
||||
if (validx == -1) throw new ArgumentException("找不到 WHERE ");
|
||||
sb.Insert(0, sql.Substring(0, validx));
|
||||
sb.Append(sql.Substring(validx));
|
||||
|
||||
sql = sb.ToString();
|
||||
var dbParms = _params.Concat(_paramsSource).ToArray();
|
||||
var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Update, sql, dbParms);
|
||||
_orm.Aop.CurdBefore?.Invoke(this, before);
|
||||
var ret = new List<T1>();
|
||||
Exception exception = null;
|
||||
try {
|
||||
ret = _orm.Ado.Query<T1>(_connection, _transaction, CommandType.Text, sql, dbParms);
|
||||
ValidateVersionAndThrow(ret.Count);
|
||||
} catch (Exception ex) {
|
||||
exception = ex;
|
||||
throw ex;
|
||||
} finally {
|
||||
var after = new Aop.CurdAfterEventArgs(before, exception, ret);
|
||||
_orm.Aop.CurdAfter?.Invoke(this, after);
|
||||
}
|
||||
this.ClearData();
|
||||
return ret;
|
||||
}
|
||||
async protected override Task<List<T1>> RawExecuteUpdatedAsync() {
|
||||
var sql = this.ToSql();
|
||||
if (string.IsNullOrEmpty(sql)) return new List<T1>();
|
||||
|
||||
var sb = new StringBuilder();
|
||||
sb.Append(" OUTPUT ");
|
||||
var colidx = 0;
|
||||
foreach (var col in _table.Columns.Values) {
|
||||
if (colidx > 0) sb.Append(", ");
|
||||
sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, $"INSERTED.{_commonUtils.QuoteSqlName(col.Attribute.Name)}")).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName));
|
||||
++colidx;
|
||||
}
|
||||
|
||||
var validx = sql.IndexOf(" WHERE ");
|
||||
if (validx == -1) throw new ArgumentException("找不到 WHERE ");
|
||||
sb.Insert(0, sql.Substring(0, validx));
|
||||
sb.Append(sql.Substring(validx));
|
||||
|
||||
sql = sb.ToString();
|
||||
var dbParms = _params.Concat(_paramsSource).ToArray();
|
||||
var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Update, sql, dbParms);
|
||||
_orm.Aop.CurdBefore?.Invoke(this, before);
|
||||
var ret = new List<T1>();
|
||||
Exception exception = null;
|
||||
try {
|
||||
ret = await _orm.Ado.QueryAsync<T1>(_connection, _transaction, CommandType.Text, sql, dbParms);
|
||||
ValidateVersionAndThrow(ret.Count);
|
||||
} catch (Exception ex) {
|
||||
exception = ex;
|
||||
throw ex;
|
||||
} finally {
|
||||
var after = new Aop.CurdAfterEventArgs(before, exception, ret);
|
||||
_orm.Aop.CurdAfter?.Invoke(this, after);
|
||||
}
|
||||
this.ClearData();
|
||||
return ret;
|
||||
}
|
||||
|
||||
protected override void ToSqlCase(StringBuilder caseWhen, ColumnInfo[] primarys) {
|
||||
if (_table.Primarys.Length == 1) {
|
||||
caseWhen.Append(_commonUtils.QuoteReadColumn(_table.Primarys.First().Attribute.MapType, _commonUtils.QuoteSqlName(_table.Primarys.First().Attribute.Name)));
|
||||
return;
|
||||
}
|
||||
caseWhen.Append("(");
|
||||
var pkidx = 0;
|
||||
foreach (var pk in _table.Primarys) {
|
||||
if (pkidx > 0) caseWhen.Append(", ");
|
||||
caseWhen.Append("cast(").Append(_commonUtils.QuoteReadColumn(_table.Primarys.First().Attribute.MapType, _commonUtils.QuoteSqlName(pk.Attribute.Name))).Append(" as varchar)");
|
||||
++pkidx;
|
||||
}
|
||||
caseWhen.Append(")");
|
||||
}
|
||||
|
||||
protected override void ToSqlWhen(StringBuilder sb, ColumnInfo[] primarys, object d) {
|
||||
if (_table.Primarys.Length == 1) {
|
||||
sb.Append(_commonUtils.FormatSql("{0}", _table.Primarys.First().GetMapValue(d)));
|
||||
return;
|
||||
}
|
||||
var pkidx = 0;
|
||||
foreach (var pk in _table.Primarys) {
|
||||
if (pkidx > 0) sb.Append(", ");
|
||||
sb.Append("cast(").Append(_commonUtils.FormatSql("{0}", pk.GetMapValue(d))).Append(" as varchar)");
|
||||
++pkidx;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<Version>0.6.1</Version>
|
||||
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
||||
<Authors>YeXiangQin</Authors>
|
||||
<Description>FreeSql 数据库实现,基于 SqlServer 2005+,并根据版本适配分页方法:row_number 或 offset fetch next</Description>
|
||||
<PackageProjectUrl>https://github.com/2881099/FreeSql</PackageProjectUrl>
|
||||
<RepositoryUrl>https://github.com/2881099/FreeSql</RepositoryUrl>
|
||||
<RepositoryType>git</RepositoryType>
|
||||
<PackageLicenseExpression>MIT</PackageLicenseExpression>
|
||||
<PackageTags>FreeSql;ORM</PackageTags>
|
||||
<PackageId>$(AssemblyName)</PackageId>
|
||||
<Title>$(AssemblyName)</Title>
|
||||
<IsPackable>true</IsPackable>
|
||||
<GenerateAssemblyInfo>true</GenerateAssemblyInfo>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="System.Data.SqlClient" Version="4.6.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\FreeSql\FreeSql.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
@ -0,0 +1,65 @@
|
||||
using FreeSql.Internal;
|
||||
using SafeObjectPool;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Data.Common;
|
||||
using System.Data.SqlClient;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
|
||||
namespace FreeSql.SqlServer {
|
||||
class SqlServerAdo : FreeSql.Internal.CommonProvider.AdoProvider {
|
||||
public SqlServerAdo() : base(DataType.SqlServer) { }
|
||||
public SqlServerAdo(CommonUtils util, string masterConnectionString, string[] slaveConnectionStrings) : base(DataType.SqlServer) {
|
||||
base._util = util;
|
||||
if (!string.IsNullOrEmpty(masterConnectionString))
|
||||
MasterPool = new SqlServerConnectionPool("主库", masterConnectionString, null, null);
|
||||
if (slaveConnectionStrings != null) {
|
||||
foreach (var slaveConnectionString in slaveConnectionStrings) {
|
||||
var slavePool = new SqlServerConnectionPool($"从库{SlavePools.Count + 1}", slaveConnectionString, () => Interlocked.Decrement(ref slaveUnavailables), () => Interlocked.Increment(ref slaveUnavailables));
|
||||
SlavePools.Add(slavePool);
|
||||
}
|
||||
}
|
||||
}
|
||||
static DateTime dt1970 = new DateTime(1970, 1, 1);
|
||||
public override object AddslashesProcessParam(object param, Type mapType) {
|
||||
if (param == null) return "NULL";
|
||||
if (mapType != null && mapType != param.GetType())
|
||||
param = Utils.GetDataReaderValue(mapType, param);
|
||||
if (param is bool || param is bool?)
|
||||
return (bool)param ? 1 : 0;
|
||||
else if (param is string || param is char)
|
||||
return string.Concat("'", param.ToString().Replace("'", "''"), "'");
|
||||
else if (param is Enum)
|
||||
return ((Enum)param).ToInt64();
|
||||
else if (decimal.TryParse(string.Concat(param), out var trydec))
|
||||
return param;
|
||||
else if (param is DateTime || param is DateTime?) {
|
||||
if (param.Equals(DateTime.MinValue) == true) param = new DateTime(1970, 1, 1);
|
||||
return string.Concat("'", ((DateTime)param).ToString("yyyy-MM-dd HH:mm:ss.fff"), "'");
|
||||
} else if (param is DateTimeOffset || param is DateTimeOffset?) {
|
||||
if (param.Equals(DateTimeOffset.MinValue) == true) param = new DateTimeOffset(new DateTime(1970, 1, 1), TimeSpan.Zero);
|
||||
return string.Concat("'", ((DateTimeOffset)param).ToString("yyyy-MM-dd HH:mm:ss.fff zzzz"), "'");
|
||||
} else if (param is TimeSpan || param is TimeSpan?)
|
||||
return ((TimeSpan)param).TotalSeconds;
|
||||
else if (param is IEnumerable) {
|
||||
var sb = new StringBuilder();
|
||||
var ie = param as IEnumerable;
|
||||
foreach (var z in ie) sb.Append(",").Append(AddslashesProcessParam(z, mapType));
|
||||
return sb.Length == 0 ? "(NULL)" : sb.Remove(0, 1).Insert(0, "(").Append(")").ToString();
|
||||
}
|
||||
return string.Concat("'", param.ToString().Replace("'", "''"), "'");
|
||||
//if (param is string) return string.Concat('N', nparms[a]);
|
||||
}
|
||||
|
||||
protected override DbCommand CreateCommand() {
|
||||
return new SqlCommand();
|
||||
}
|
||||
|
||||
protected override void ReturnConnection(ObjectPool<DbConnection> pool, Object<DbConnection> conn, Exception ex) {
|
||||
(pool as SqlServerConnectionPool).Return(conn, ex);
|
||||
}
|
||||
|
||||
protected override DbParameter[] GetDbParamtersByObject(string sql, object obj) => _util.GetDbParamtersByObject(sql, obj);
|
||||
}
|
||||
}
|
@ -0,0 +1,181 @@
|
||||
using SafeObjectPool;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
using System.Data.SqlClient;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace FreeSql.SqlServer {
|
||||
|
||||
class SqlServerConnectionPool : ObjectPool<DbConnection> {
|
||||
|
||||
internal Action availableHandler;
|
||||
internal Action unavailableHandler;
|
||||
|
||||
public SqlServerConnectionPool(string name, string connectionString, Action availableHandler, Action unavailableHandler) : base(null) {
|
||||
var policy = new SqlServerConnectionPoolPolicy {
|
||||
_pool = this,
|
||||
Name = name
|
||||
};
|
||||
this.Policy = policy;
|
||||
policy.ConnectionString = connectionString;
|
||||
|
||||
this.availableHandler = availableHandler;
|
||||
this.unavailableHandler = unavailableHandler;
|
||||
}
|
||||
|
||||
public void Return(Object<DbConnection> obj, Exception exception, bool isRecreate = false) {
|
||||
if (exception != null && exception is SqlException) {
|
||||
|
||||
if (obj.Value.Ping() == false) {
|
||||
|
||||
base.SetUnavailable(exception);
|
||||
}
|
||||
}
|
||||
base.Return(obj, isRecreate);
|
||||
}
|
||||
}
|
||||
|
||||
class SqlServerConnectionPoolPolicy : IPolicy<DbConnection> {
|
||||
|
||||
internal SqlServerConnectionPool _pool;
|
||||
public string Name { get; set; } = "SqlServer SqlConnection 对象池";
|
||||
public int PoolSize { get; set; } = 100;
|
||||
public TimeSpan SyncGetTimeout { get; set; } = TimeSpan.FromSeconds(10);
|
||||
public TimeSpan IdleTimeout { get; set; } = TimeSpan.Zero;
|
||||
public int AsyncGetCapacity { get; set; } = 10000;
|
||||
public bool IsThrowGetTimeoutException { get; set; } = true;
|
||||
public int CheckAvailableInterval { get; set; } = 5;
|
||||
|
||||
static ConcurrentDictionary<string, int> dicConnStrIncr = new ConcurrentDictionary<string, int>(StringComparer.CurrentCultureIgnoreCase);
|
||||
private string _connectionString;
|
||||
public string ConnectionString {
|
||||
get => _connectionString;
|
||||
set {
|
||||
_connectionString = value ?? "";
|
||||
|
||||
var pattern = @"Max\s*pool\s*size\s*=\s*(\d+)";
|
||||
Match m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase);
|
||||
if (m.Success == false || int.TryParse(m.Groups[1].Value, out var poolsize) == false || poolsize <= 0) poolsize = 100;
|
||||
var connStrIncr = dicConnStrIncr.AddOrUpdate(_connectionString, 1, (oldkey, oldval) => oldval + 1);
|
||||
PoolSize = poolsize + connStrIncr;
|
||||
_connectionString = m.Success ?
|
||||
Regex.Replace(_connectionString, pattern, $"Max pool size={PoolSize}", RegexOptions.IgnoreCase) :
|
||||
$"{_connectionString};Max pool size={PoolSize}";
|
||||
|
||||
pattern = @"Connection\s*LifeTime\s*=\s*(\d+)";
|
||||
m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase);
|
||||
if (m.Success) {
|
||||
IdleTimeout = TimeSpan.FromSeconds(int.Parse(m.Groups[1].Value));
|
||||
_connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase);
|
||||
}
|
||||
|
||||
var minPoolSize = 0;
|
||||
pattern = @"Min\s*pool\s*size\s*=\s*(\d+)";
|
||||
m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase);
|
||||
if (m.Success) {
|
||||
minPoolSize = int.Parse(m.Groups[1].Value);
|
||||
_connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase);
|
||||
}
|
||||
|
||||
FreeSql.Internal.CommonUtils.PrevReheatConnectionPool(_pool, minPoolSize);
|
||||
}
|
||||
}
|
||||
|
||||
public bool OnCheckAvailable(Object<DbConnection> obj) {
|
||||
if (obj.Value.State == ConnectionState.Closed) obj.Value.Open();
|
||||
return obj.Value.Ping(true);
|
||||
}
|
||||
|
||||
public DbConnection OnCreate() {
|
||||
var conn = new SqlConnection(_connectionString);
|
||||
return conn;
|
||||
}
|
||||
|
||||
public void OnDestroy(DbConnection obj) {
|
||||
if (obj.State != ConnectionState.Closed) obj.Close();
|
||||
obj.Dispose();
|
||||
}
|
||||
|
||||
public void OnGet(Object<DbConnection> obj) {
|
||||
|
||||
if (_pool.IsAvailable) {
|
||||
|
||||
if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && obj.Value.Ping() == false) {
|
||||
|
||||
try {
|
||||
obj.Value.Open();
|
||||
} catch (Exception ex) {
|
||||
if (_pool.SetUnavailable(ex) == true)
|
||||
throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async public Task OnGetAsync(Object<DbConnection> obj) {
|
||||
|
||||
if (_pool.IsAvailable) {
|
||||
|
||||
if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && (await obj.Value.PingAsync()) == false) {
|
||||
|
||||
try {
|
||||
await obj.Value.OpenAsync();
|
||||
} catch (Exception ex) {
|
||||
if (_pool.SetUnavailable(ex) == true)
|
||||
throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void OnGetTimeout() {
|
||||
|
||||
}
|
||||
|
||||
public void OnReturn(Object<DbConnection> obj) {
|
||||
if (obj.Value.State != ConnectionState.Closed) try { obj.Value.Close(); } catch { }
|
||||
}
|
||||
|
||||
public void OnAvailable() {
|
||||
_pool.availableHandler?.Invoke();
|
||||
}
|
||||
|
||||
public void OnUnavailable() {
|
||||
_pool.unavailableHandler?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
static class DbConnectionExtensions {
|
||||
|
||||
static DbCommand PingCommand(DbConnection conn) {
|
||||
var cmd = conn.CreateCommand();
|
||||
cmd.CommandTimeout = 5;
|
||||
cmd.CommandText = "select 1";
|
||||
return cmd;
|
||||
}
|
||||
public static bool Ping(this DbConnection that, bool isThrow = false) {
|
||||
try {
|
||||
PingCommand(that).ExecuteNonQuery();
|
||||
return true;
|
||||
} catch {
|
||||
if (that.State != ConnectionState.Closed) try { that.Close(); } catch { }
|
||||
if (isThrow) throw;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
async public static Task<bool> PingAsync(this DbConnection that, bool isThrow = false) {
|
||||
try {
|
||||
await PingCommand(that).ExecuteNonQueryAsync();
|
||||
return true;
|
||||
} catch {
|
||||
if (that.State != ConnectionState.Closed) try { that.Close(); } catch { }
|
||||
if (isThrow) throw;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
366
Providers/FreeSql.Provider.SqlServer/SqlServerCodeFirst.cs
Normal file
366
Providers/FreeSql.Provider.SqlServer/SqlServerCodeFirst.cs
Normal file
@ -0,0 +1,366 @@
|
||||
using FreeSql.DataAnnotations;
|
||||
using FreeSql.DatabaseModel;
|
||||
using FreeSql.Internal;
|
||||
using FreeSql.Internal.Model;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace FreeSql.SqlServer {
|
||||
|
||||
class SqlServerCodeFirst : ICodeFirst {
|
||||
IFreeSql _orm;
|
||||
protected CommonUtils _commonUtils;
|
||||
protected CommonExpression _commonExpression;
|
||||
public SqlServerCodeFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) {
|
||||
_orm = orm;
|
||||
_commonUtils = commonUtils;
|
||||
_commonExpression = commonExpression;
|
||||
}
|
||||
|
||||
public bool IsAutoSyncStructure { get; set; } = false;
|
||||
public bool IsSyncStructureToLower { get; set; } = false;
|
||||
public bool IsSyncStructureToUpper { get; set; } = false;
|
||||
public bool IsConfigEntityFromDbFirst { get; set; } = false;
|
||||
public bool IsNoneCommandParameter { get; set; } = false;
|
||||
public bool IsLazyLoading { get; set; } = false;
|
||||
|
||||
static object _dicCsToDbLock = new object();
|
||||
static Dictionary<string, (SqlDbType type, string dbtype, string dbtypeFull, bool? isUnsigned, bool? isnullable, object defaultValue)> _dicCsToDb = new Dictionary<string, (SqlDbType type, string dbtype, string dbtypeFull, bool? isUnsigned, bool? isnullable, object defaultValue)>() {
|
||||
{ typeof(bool).FullName, (SqlDbType.Bit, "bit","bit NOT NULL", null, false, false) },{ typeof(bool?).FullName, (SqlDbType.Bit, "bit","bit", null, true, null) },
|
||||
|
||||
{ typeof(sbyte).FullName, (SqlDbType.SmallInt, "smallint", "smallint NOT NULL", false, false, 0) },{ typeof(sbyte?).FullName, (SqlDbType.SmallInt, "smallint", "smallint", false, true, null) },
|
||||
{ typeof(short).FullName, (SqlDbType.SmallInt, "smallint","smallint NOT NULL", false, false, 0) },{ typeof(short?).FullName, (SqlDbType.SmallInt, "smallint", "smallint", false, true, null) },
|
||||
{ typeof(int).FullName, (SqlDbType.Int, "int", "int NOT NULL", false, false, 0) },{ typeof(int?).FullName, (SqlDbType.Int, "int", "int", false, true, null) },
|
||||
{ typeof(long).FullName, (SqlDbType.BigInt, "bigint","bigint NOT NULL", false, false, 0) },{ typeof(long?).FullName, (SqlDbType.BigInt, "bigint","bigint", false, true, null) },
|
||||
|
||||
{ typeof(byte).FullName, (SqlDbType.TinyInt, "tinyint","tinyint NOT NULL", true, false, 0) },{ typeof(byte?).FullName, (SqlDbType.TinyInt, "tinyint","tinyint", true, true, null) },
|
||||
{ typeof(ushort).FullName, (SqlDbType.Int, "int","int NOT NULL", true, false, 0) },{ typeof(ushort?).FullName, (SqlDbType.Int, "int", "int", true, true, null) },
|
||||
{ typeof(uint).FullName, (SqlDbType.BigInt, "bigint", "bigint NOT NULL", true, false, 0) },{ typeof(uint?).FullName, (SqlDbType.BigInt, "bigint", "bigint", true, true, null) },
|
||||
{ typeof(ulong).FullName, (SqlDbType.Decimal, "decimal", "decimal(20,0) NOT NULL", true, false, 0) },{ typeof(ulong?).FullName, (SqlDbType.Decimal, "decimal", "decimal(20,0)", true, true, null) },
|
||||
|
||||
{ typeof(double).FullName, (SqlDbType.Float, "float", "float NOT NULL", false, false, 0) },{ typeof(double?).FullName, (SqlDbType.Float, "float", "float", false, true, null) },
|
||||
{ typeof(float).FullName, (SqlDbType.Real, "real","real NOT NULL", false, false, 0) },{ typeof(float?).FullName, (SqlDbType.Real, "real","real", false, true, null) },
|
||||
{ typeof(decimal).FullName, (SqlDbType.Decimal, "decimal", "decimal(10,2) NOT NULL", false, false, 0) },{ typeof(decimal?).FullName, (SqlDbType.Decimal, "decimal", "decimal(10,2)", false, true, null) },
|
||||
|
||||
{ typeof(TimeSpan).FullName, (SqlDbType.Time, "time","time NOT NULL", false, false, 0) },{ typeof(TimeSpan?).FullName, (SqlDbType.Time, "time", "time",false, true, null) },
|
||||
{ typeof(DateTime).FullName, (SqlDbType.DateTime, "datetime", "datetime NOT NULL", false, false, new DateTime(1970,1,1)) },{ typeof(DateTime?).FullName, (SqlDbType.DateTime, "datetime", "datetime", false, true, null) },
|
||||
{ typeof(DateTimeOffset).FullName, (SqlDbType.DateTimeOffset, "datetimeoffset", "datetimeoffset NOT NULL", false, false, new DateTimeOffset(new DateTime(1970,1,1), TimeSpan.Zero)) },{ typeof(DateTimeOffset?).FullName, (SqlDbType.DateTimeOffset, "datetimeoffset", "datetimeoffset", false, true, null) },
|
||||
|
||||
{ typeof(byte[]).FullName, (SqlDbType.VarBinary, "varbinary", "varbinary(255)", false, null, new byte[0]) },
|
||||
{ typeof(string).FullName, (SqlDbType.NVarChar, "nvarchar", "nvarchar(255)", false, null, "") },
|
||||
|
||||
{ typeof(Guid).FullName, (SqlDbType.UniqueIdentifier, "uniqueidentifier", "uniqueidentifier NOT NULL", false, false, Guid.Empty) },{ typeof(Guid?).FullName, (SqlDbType.UniqueIdentifier, "uniqueidentifier", "uniqueidentifier", false, true, null) },
|
||||
};
|
||||
|
||||
public (int type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfo(Type type) {
|
||||
if (_dicCsToDb.TryGetValue(type.FullName, out var trydc)) return new (int, string, string, bool?, object)?(((int)trydc.type, trydc.dbtype, trydc.dbtypeFull, trydc.isnullable, trydc.defaultValue));
|
||||
if (type.IsArray) return null;
|
||||
var enumType = type.IsEnum ? type : null;
|
||||
if (enumType == null && type.IsNullableType() && type.GenericTypeArguments.Length == 1 && type.GenericTypeArguments.First().IsEnum) enumType = type.GenericTypeArguments.First();
|
||||
if (enumType != null) {
|
||||
var newItem = enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Any() ?
|
||||
(SqlDbType.BigInt, "bigint", $"bigint{(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0)) :
|
||||
(SqlDbType.Int, "int", $"int{(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0));
|
||||
if (_dicCsToDb.ContainsKey(type.FullName) == false) {
|
||||
lock (_dicCsToDbLock) {
|
||||
if (_dicCsToDb.ContainsKey(type.FullName) == false)
|
||||
_dicCsToDb.Add(type.FullName, newItem);
|
||||
}
|
||||
}
|
||||
return ((int)newItem.Item1, newItem.Item2, newItem.Item3, newItem.Item5, newItem.Item6);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public string GetComparisonDDLStatements<TEntity>() => this.GetComparisonDDLStatements(typeof(TEntity));
|
||||
public string GetComparisonDDLStatements(params Type[] entityTypes) {
|
||||
var conn = _orm.Ado.MasterPool.Get(TimeSpan.FromSeconds(5));
|
||||
var database = conn.Value.Database;
|
||||
Func<string, string, object> ExecuteScalar = (db, sql) => {
|
||||
if (string.Compare(database, db) != 0) conn.Value.ChangeDatabase(db);
|
||||
try {
|
||||
using (var cmd = conn.Value.CreateCommand()) {
|
||||
cmd.CommandText = sql;
|
||||
cmd.CommandType = CommandType.Text;
|
||||
return cmd.ExecuteScalar();
|
||||
}
|
||||
} finally {
|
||||
if (string.Compare(database, db) != 0) conn.Value.ChangeDatabase(database);
|
||||
}
|
||||
};
|
||||
var sb = new StringBuilder();
|
||||
try {
|
||||
foreach (var entityType in entityTypes) {
|
||||
if (sb.Length > 0) sb.Append("\r\n");
|
||||
var tb = _commonUtils.GetTableByEntity(entityType);
|
||||
if (tb == null) throw new Exception($"类型 {entityType.FullName} 不可迁移");
|
||||
if (tb.Columns.Any() == false) throw new Exception($"类型 {entityType.FullName} 不可迁移,可迁移属性0个");
|
||||
var tbname = tb.DbName.Split(new[] { '.' }, 3);
|
||||
if (tbname?.Length == 1) tbname = new[] { database, "dbo", tbname[0] };
|
||||
if (tbname?.Length == 2) tbname = new[] { database, tbname[0], tbname[1] };
|
||||
|
||||
var tboldname = tb.DbOldName?.Split(new[] { '.' }, 3); //旧表名
|
||||
if (tboldname?.Length == 1) tboldname = new[] { database, "dbo", tboldname[0] };
|
||||
if (tboldname?.Length == 2) tboldname = new[] { database, tboldname[0], tboldname[1] };
|
||||
|
||||
if (string.Compare(tbname[0], database, true) != 0 && ExecuteScalar(database, $" select 1 from sys.databases where name='{tbname[0]}'") == null) //创建数据库
|
||||
ExecuteScalar(database, $"if not exists(select 1 from sys.databases where name='{tbname[0]}')\r\n\tcreate database [{tbname[0]}];");
|
||||
if (string.Compare(tbname[1], "dbo", true) != 0 && ExecuteScalar(tbname[0], $" select 1 from sys.schemas where name='{tbname[1]}'") == null) //创建模式
|
||||
ExecuteScalar(tbname[0], $"create schema [{tbname[1]}] authorization [dbo]");
|
||||
|
||||
var sbalter = new StringBuilder();
|
||||
var istmpatler = false; //创建临时表,导入数据,删除旧表,修改
|
||||
if (ExecuteScalar(tbname[0], $" select 1 from dbo.sysobjects where id = object_id(N'[{tbname[1]}].[{tbname[2]}]') and OBJECTPROPERTY(id, N'IsUserTable') = 1") == null) { //表不存在
|
||||
if (tboldname != null) {
|
||||
if (string.Compare(tboldname[0], tbname[0], true) != 0 && ExecuteScalar(database, $" select 1 from sys.databases where name='{tboldname[0]}'") == null ||
|
||||
string.Compare(tboldname[1], tbname[1], true) != 0 && ExecuteScalar(tboldname[0], $" select 1 from sys.schemas where name='{tboldname[1]}'") == null ||
|
||||
ExecuteScalar(tboldname[0], $" select 1 from dbo.sysobjects where id = object_id(N'[{tboldname[1]}].[{tboldname[2]}]') and OBJECTPROPERTY(id, N'IsUserTable') = 1") == null)
|
||||
//数据库或模式或表不存在
|
||||
tboldname = null;
|
||||
}
|
||||
if (tboldname == null) {
|
||||
//创建新表
|
||||
sb.Append("use ").Append(_commonUtils.QuoteSqlName(tbname[0])).Append(";\r\nCREATE TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}.{tbname[2]}")).Append(" ( ");
|
||||
var pkidx = 0;
|
||||
foreach (var tbcol in tb.Columns.Values) {
|
||||
sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ");
|
||||
sb.Append(tbcol.Attribute.DbType);
|
||||
if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" identity(1,1)");
|
||||
if (tbcol.Attribute.IsPrimary == true) {
|
||||
if (tb.Primarys.Length > 1) {
|
||||
if (pkidx == tb.Primarys.Length - 1)
|
||||
sb.Append(" primary key (").Append(string.Join(", ", tb.Primarys.Select(a => _commonUtils.QuoteSqlName(a.Attribute.Name)))).Append(")");
|
||||
} else
|
||||
sb.Append(" primary key");
|
||||
pkidx++;
|
||||
}
|
||||
sb.Append(",");
|
||||
}
|
||||
foreach (var uk in tb.Uniques) {
|
||||
sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE(");
|
||||
foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
sb.Remove(sb.Length - 1, 1).Append("\r\n);\r\n");
|
||||
continue;
|
||||
}
|
||||
//如果新表,旧表在一个数据库和模式下,直接修改表名
|
||||
if (string.Compare(tbname[0], tboldname[0], true) == 0 &&
|
||||
string.Compare(tbname[1], tboldname[1], true) == 0)
|
||||
sbalter.Append("use ").Append(_commonUtils.QuoteSqlName(tbname[0])).Append(_commonUtils.FormatSql(";\r\nEXEC sp_rename {0}, {1};\r\n", _commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}.{tboldname[2]}"), tbname[2]));
|
||||
else {
|
||||
//如果新表,旧表不在一起,创建新表,导入数据,删除旧表
|
||||
istmpatler = true;
|
||||
}
|
||||
} else
|
||||
tboldname = null; //如果新表已经存在,不走改表名逻辑
|
||||
|
||||
//对比字段,只可以修改类型、增加字段、有限的修改字段名;保证安全不删除字段
|
||||
var sql = string.Format(@"
|
||||
use [{0}];
|
||||
select
|
||||
a.name 'Column'
|
||||
,b.name + case
|
||||
when b.name in ('Char', 'VarChar', 'NChar', 'NVarChar', 'Binary', 'VarBinary') then '(' +
|
||||
case when a.max_length = -1 then 'MAX'
|
||||
when b.name in ('NChar', 'NVarchar') then cast(a.max_length / 2 as varchar)
|
||||
else cast(a.max_length as varchar) end + ')'
|
||||
when b.name in ('Numeric', 'Decimal') then '(' + cast(a.precision as varchar) + ',' + cast(a.scale as varchar) + ')'
|
||||
else '' end as 'SqlType'
|
||||
,case when a.is_nullable = 1 then '1' else '0' end 'IsNullable'
|
||||
,case when a.is_identity = 1 then '1' else '0' end 'IsIdentity'
|
||||
from sys.columns a
|
||||
inner join sys.types b on b.user_type_id = a.user_type_id
|
||||
left join sys.extended_properties AS c ON c.major_id = a.object_id AND c.minor_id = a.column_id
|
||||
left join sys.tables d on d.object_id = a.object_id
|
||||
left join sys.schemas e on e.schema_id = d.schema_id
|
||||
where a.object_id in (object_id(N'[{1}].[{2}]'));
|
||||
use " + database, tboldname ?? tbname);
|
||||
var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql);
|
||||
var tbstruct = ds.ToDictionary(a => string.Concat(a[0]), a => new {
|
||||
column = string.Concat(a[0]),
|
||||
sqlType = string.Concat(a[1]),
|
||||
is_nullable = string.Concat(a[2]) == "1",
|
||||
is_identity = string.Concat(a[3]) == "1"
|
||||
}, StringComparer.CurrentCultureIgnoreCase);
|
||||
|
||||
if (istmpatler == false) {
|
||||
foreach (var tbcol in tb.Columns.Values) {
|
||||
if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) ||
|
||||
string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) {
|
||||
if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false ||
|
||||
tbcol.Attribute.IsNullable != tbstructcol.is_nullable ||
|
||||
tbcol.Attribute.IsIdentity != tbstructcol.is_identity) {
|
||||
istmpatler = true;
|
||||
break;
|
||||
}
|
||||
if (tbstructcol.column == tbcol.Attribute.OldName) {
|
||||
//修改列名
|
||||
sbalter.Append(_commonUtils.FormatSql("EXEC sp_rename {0}, {1}, 'COLUMN';\r\n", $"{tbname[0]}.{tbname[1]}.{tbname[2]}.{tbcol.Attribute.OldName}", tbcol.Attribute.Name));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
//添加列
|
||||
sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbname[2]}")).Append(" ADD ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType);
|
||||
if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sbalter.Append(" identity(1,1)");
|
||||
if (tbcol.Attribute.IsNullable == false) {
|
||||
var addcoldbdefault = tbcol.Attribute.DbDefautValue;
|
||||
if (addcoldbdefault != null) sbalter.Append(_commonUtils.FormatSql(" default({0})", addcoldbdefault));
|
||||
}
|
||||
sbalter.Append(";\r\n");
|
||||
}
|
||||
var dsuksql = string.Format(@"
|
||||
use [{0}];
|
||||
select
|
||||
c.name
|
||||
,d.name
|
||||
from sys.index_columns a
|
||||
inner join sys.indexes b on b.object_id = a.object_id and b.index_id = a.index_id
|
||||
left join sys.columns c on c.object_id = a.object_id and c.column_id = a.column_id
|
||||
left join sys.key_constraints d on d.parent_object_id = b.object_id and d.unique_index_id = b.index_id
|
||||
where a.object_id in (object_id(N'[{1}].[{2}]')) and b.is_unique = 1;
|
||||
use " + database, tboldname ?? tbname);
|
||||
var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]) });
|
||||
foreach (var uk in tb.Uniques) {
|
||||
if (string.IsNullOrEmpty(uk.Key) || uk.Value.Any() == false) continue;
|
||||
var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Key, true) == 0).ToArray();
|
||||
if (dsukfind1.Any() == false || dsukfind1.Length != uk.Value.Count || dsukfind1.Where(a => uk.Value.Where(b => string.Compare(b.Attribute.Name, a[0], true) == 0).Any()).Count() != uk.Value.Count) {
|
||||
if (dsukfind1.Any()) sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbname[2]}")).Append(" DROP CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(";\r\n");
|
||||
sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbname[2]}")).Append(" ADD CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE(");
|
||||
foreach (var tbcol in uk.Value) sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sbalter.Remove(sbalter.Length - 2, 2).Append(");\r\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (istmpatler == false) {
|
||||
sb.Append(sbalter).Append("\r\nuse " + database);
|
||||
continue;
|
||||
}
|
||||
//创建临时表,数据导进临时表,然后删除原表,将临时表改名为原表名
|
||||
bool idents = false;
|
||||
var tablename = tboldname == null ? _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbname[2]}") : _commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}.{tboldname[2]}");
|
||||
var tmptablename = _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.FreeSqlTmp_{tbname[2]}");
|
||||
sb.Append("BEGIN TRANSACTION\r\n")
|
||||
.Append("SET QUOTED_IDENTIFIER ON\r\n")
|
||||
.Append("SET ARITHABORT ON\r\n")
|
||||
.Append("SET NUMERIC_ROUNDABORT OFF\r\n")
|
||||
.Append("SET CONCAT_NULL_YIELDS_NULL ON\r\n")
|
||||
.Append("SET ANSI_NULLS ON\r\n")
|
||||
.Append("SET ANSI_PADDING ON\r\n")
|
||||
.Append("SET ANSI_WARNINGS ON\r\n")
|
||||
.Append("COMMIT\r\n");
|
||||
sb.Append("BEGIN TRANSACTION;\r\n");
|
||||
//创建临时表
|
||||
sb.Append("CREATE TABLE ").Append(tmptablename).Append(" ( ");
|
||||
var pkidx2 = 0;
|
||||
foreach (var tbcol in tb.Columns.Values) {
|
||||
sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ");
|
||||
sb.Append(tbcol.Attribute.DbType);
|
||||
if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" identity(1,1)");
|
||||
if (tbcol.Attribute.IsPrimary == true) {
|
||||
if (tb.Primarys.Length > 1) {
|
||||
if (pkidx2 == tb.Primarys.Length - 1)
|
||||
sb.Append(" primary key (").Append(string.Join(", ", tb.Primarys.Select(a => _commonUtils.QuoteSqlName(a.Attribute.Name)))).Append(")");
|
||||
} else
|
||||
sb.Append(" primary key");
|
||||
pkidx2++;
|
||||
}
|
||||
sb.Append(",");
|
||||
idents = idents || tbcol.Attribute.IsIdentity == true;
|
||||
}
|
||||
foreach (var uk in tb.Uniques) {
|
||||
sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE(");
|
||||
foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
sb.Remove(sb.Length - 1, 1).Append("\r\n);\r\n");
|
||||
sb.Append("ALTER TABLE ").Append(tmptablename).Append(" SET (LOCK_ESCALATION = TABLE);\r\n");
|
||||
if (idents) sb.Append("SET IDENTITY_INSERT ").Append(tmptablename).Append(" ON;\r\n");
|
||||
sb.Append("IF EXISTS(SELECT 1 FROM ").Append(tablename).Append(")\r\n");
|
||||
sb.Append("\tEXEC('INSERT INTO ").Append(tmptablename).Append(" (");
|
||||
foreach (var tbcol in tb.Columns.Values)
|
||||
sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append(")\r\n\t\tSELECT ");
|
||||
foreach (var tbcol in tb.Columns.Values) {
|
||||
var insertvalue = "NULL";
|
||||
if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) ||
|
||||
string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) {
|
||||
insertvalue = _commonUtils.QuoteSqlName(tbstructcol.column);
|
||||
if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false)
|
||||
insertvalue = $"cast({insertvalue} as {tbcol.Attribute.DbType.Split(' ').First()})";
|
||||
if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable)
|
||||
insertvalue = $"isnull({insertvalue},{_commonUtils.FormatSql("{0}", GetTransferDbDefaultValue(tbcol))})";
|
||||
} else if (tbcol.Attribute.IsNullable == false)
|
||||
insertvalue = _commonUtils.FormatSql("{0}", GetTransferDbDefaultValue(tbcol));
|
||||
sb.Append(insertvalue.Replace("'", "''")).Append(", ");
|
||||
}
|
||||
sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(" WITH (HOLDLOCK TABLOCKX)');\r\n");
|
||||
if (idents) sb.Append("SET IDENTITY_INSERT ").Append(tmptablename).Append(" OFF;\r\n");
|
||||
sb.Append("DROP TABLE ").Append(tablename).Append(";\r\n");
|
||||
sb.Append("EXECUTE sp_rename N'").Append(tmptablename).Append("', N'").Append(tbname[2]).Append("', 'OBJECT';\r\n");
|
||||
sb.Append("COMMIT;\r\n");
|
||||
}
|
||||
return sb.Length == 0 ? null : sb.ToString();
|
||||
} finally {
|
||||
try {
|
||||
conn.Value.ChangeDatabase(database);
|
||||
_orm.Ado.MasterPool.Return(conn);
|
||||
} catch {
|
||||
_orm.Ado.MasterPool.Return(conn, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
object GetTransferDbDefaultValue(ColumnInfo col) {
|
||||
var ddv = col.Attribute.DbDefautValue;
|
||||
if (ddv == null) return ddv;
|
||||
if (ddv is DateTime || ddv is DateTime?) {
|
||||
var dt = (DateTime)ddv;
|
||||
if (col.Attribute.DbType.Contains("SMALLDATETIME") && dt < new DateTime(1900, 1, 1)) ddv = new DateTime(1900, 1, 1);
|
||||
else if (col.Attribute.DbType.Contains("DATETIME") && dt < new DateTime(1753, 1, 1)) ddv = new DateTime(1753, 1, 1);
|
||||
else if (col.Attribute.DbType.Contains("DATE") && dt < new DateTime(0001, 1, 1)) ddv = new DateTime(0001, 1, 1);
|
||||
}
|
||||
return ddv;
|
||||
}
|
||||
|
||||
|
||||
static object syncStructureLock = new object();
|
||||
ConcurrentDictionary<string, bool> dicSyced = new ConcurrentDictionary<string, bool>();
|
||||
public bool SyncStructure<TEntity>() => this.SyncStructure(typeof(TEntity));
|
||||
public bool SyncStructure(params Type[] entityTypes) {
|
||||
if (entityTypes == null) return true;
|
||||
var syncTypes = entityTypes.Where(a => dicSyced.ContainsKey(a.FullName) == false).ToArray();
|
||||
if (syncTypes.Any() == false) return true;
|
||||
var before = new Aop.SyncStructureBeforeEventArgs(entityTypes);
|
||||
_orm.Aop.SyncStructureBefore?.Invoke(this, before);
|
||||
Exception exception = null;
|
||||
string ddl = null;
|
||||
try {
|
||||
lock (syncStructureLock) {
|
||||
ddl = this.GetComparisonDDLStatements(syncTypes);
|
||||
if (string.IsNullOrEmpty(ddl)) {
|
||||
foreach (var syncType in syncTypes) dicSyced.TryAdd(syncType.FullName, true);
|
||||
return true;
|
||||
}
|
||||
var affrows = _orm.Ado.ExecuteNonQuery(CommandType.Text, ddl);
|
||||
foreach (var syncType in syncTypes) dicSyced.TryAdd(syncType.FullName, true);
|
||||
return affrows > 0;
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
exception = ex;
|
||||
throw ex;
|
||||
} finally {
|
||||
var after = new Aop.SyncStructureAfterEventArgs(before, ddl, exception);
|
||||
_orm.Aop.SyncStructureAfter?.Invoke(this, after);
|
||||
}
|
||||
}
|
||||
public ICodeFirst ConfigEntity<T>(Action<TableFluent<T>> entity) => _commonUtils.ConfigEntity(entity);
|
||||
public ICodeFirst ConfigEntity(Type type, Action<TableFluent> entity) => _commonUtils.ConfigEntity(type, entity);
|
||||
public TableAttribute GetConfigEntity(Type type) => _commonUtils.GetConfigEntity(type);
|
||||
public TableInfo GetTableByEntity(Type type) => _commonUtils.GetTableByEntity(type);
|
||||
}
|
||||
}
|
418
Providers/FreeSql.Provider.SqlServer/SqlServerDbFirst.cs
Normal file
418
Providers/FreeSql.Provider.SqlServer/SqlServerDbFirst.cs
Normal file
@ -0,0 +1,418 @@
|
||||
using FreeSql.DatabaseModel;
|
||||
using FreeSql.Internal;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace FreeSql.SqlServer {
|
||||
class SqlServerDbFirst : IDbFirst {
|
||||
IFreeSql _orm;
|
||||
protected CommonUtils _commonUtils;
|
||||
protected CommonExpression _commonExpression;
|
||||
public SqlServerDbFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) {
|
||||
_orm = orm;
|
||||
_commonUtils = commonUtils;
|
||||
_commonExpression = commonExpression;
|
||||
}
|
||||
|
||||
public int GetDbType(DbColumnInfo column) => (int)GetSqlDbType(column);
|
||||
SqlDbType GetSqlDbType(DbColumnInfo column) {
|
||||
switch (column.DbTypeText.ToLower()) {
|
||||
case "bit": return SqlDbType.Bit;
|
||||
case "tinyint": return SqlDbType.TinyInt;
|
||||
case "smallint": return SqlDbType.SmallInt;
|
||||
case "int": return SqlDbType.Int;
|
||||
case "bigint": return SqlDbType.BigInt;
|
||||
case "numeric":
|
||||
case "decimal": return SqlDbType.Decimal;
|
||||
case "smallmoney": return SqlDbType.SmallMoney;
|
||||
case "money": return SqlDbType.Money;
|
||||
case "float": return SqlDbType.Float;
|
||||
case "real": return SqlDbType.Real;
|
||||
case "date": return SqlDbType.Date;
|
||||
case "datetime":
|
||||
case "datetime2": return SqlDbType.DateTime;
|
||||
case "datetimeoffset": return SqlDbType.DateTimeOffset;
|
||||
case "smalldatetime": return SqlDbType.SmallDateTime;
|
||||
case "time": return SqlDbType.Time;
|
||||
case "char": return SqlDbType.Char;
|
||||
case "varchar": return SqlDbType.VarChar;
|
||||
case "text": return SqlDbType.Text;
|
||||
case "nchar": return SqlDbType.NChar;
|
||||
case "nvarchar": return SqlDbType.NVarChar;
|
||||
case "ntext": return SqlDbType.NText;
|
||||
case "binary": return SqlDbType.Binary;
|
||||
case "varbinary": return SqlDbType.VarBinary;
|
||||
case "image": return SqlDbType.Image;
|
||||
case "timestamp": return SqlDbType.Timestamp;
|
||||
case "uniqueidentifier": return SqlDbType.UniqueIdentifier;
|
||||
default: return SqlDbType.Variant;
|
||||
}
|
||||
}
|
||||
|
||||
static readonly Dictionary<int, (string csConvert, string csParse, string csStringify, string csType, Type csTypeInfo, Type csNullableTypeInfo, string csTypeValue, string dataReaderMethod)> _dicDbToCs = new Dictionary<int, (string csConvert, string csParse, string csStringify, string csType, Type csTypeInfo, Type csNullableTypeInfo, string csTypeValue, string dataReaderMethod)>() {
|
||||
{ (int)SqlDbType.Bit, ("(bool?)", "{0} == \"1\"", "{0} == true ? \"1\" : \"0\"", "bool?", typeof(bool), typeof(bool?), "{0}.Value", "GetBoolean") },
|
||||
|
||||
{ (int)SqlDbType.TinyInt, ("(byte?)", "byte.Parse({0})", "{0}.ToString()", "byte?", typeof(byte), typeof(byte?), "{0}.Value", "GetByte") },
|
||||
{ (int)SqlDbType.SmallInt, ("(short?)", "short.Parse({0})", "{0}.ToString()", "short?", typeof(short), typeof(short?), "{0}.Value", "GetInt16") },
|
||||
{ (int)SqlDbType.Int, ("(int?)", "int.Parse({0})", "{0}.ToString()", "int?", typeof(int), typeof(int?), "{0}.Value", "GetInt32") },
|
||||
{ (int)SqlDbType.BigInt, ("(long?)", "long.Parse({0})", "{0}.ToString()", "long?", typeof(long), typeof(long?), "{0}.Value", "GetInt64") },
|
||||
|
||||
{ (int)SqlDbType.SmallMoney, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") },
|
||||
{ (int)SqlDbType.Money, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") },
|
||||
{ (int)SqlDbType.Decimal, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") },
|
||||
{ (int)SqlDbType.Float, ("(double?)", "double.Parse({0})", "{0}.ToString()", "double?", typeof(double), typeof(double?), "{0}.Value", "GetDouble") },
|
||||
{ (int)SqlDbType.Real, ("(float?)", "float.Parse({0})", "{0}.ToString()", "float?", typeof(float), typeof(float?), "{0}.Value", "GetFloat") },
|
||||
|
||||
{ (int)SqlDbType.Time, ("(TimeSpan?)", "TimeSpan.Parse(double.Parse({0}))", "{0}.Ticks.ToString()", "TimeSpan?", typeof(TimeSpan), typeof(TimeSpan?), "{0}.Value", "GetValue") },
|
||||
{ (int)SqlDbType.Date, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") },
|
||||
{ (int)SqlDbType.DateTime, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") },
|
||||
{ (int)SqlDbType.DateTime2, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") },
|
||||
{ (int)SqlDbType.SmallDateTime, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") },
|
||||
{ (int)SqlDbType.DateTimeOffset, ("(DateTimeOffset?)", "new DateTimeOffset(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTimeOffset), typeof(DateTimeOffset?), "{0}.Value", "GetDateTimeOffset") },
|
||||
|
||||
{ (int)SqlDbType.Binary, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") },
|
||||
{ (int)SqlDbType.VarBinary, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") },
|
||||
{ (int)SqlDbType.Image, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") },
|
||||
{ (int)SqlDbType.Timestamp, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") },
|
||||
|
||||
{ (int)SqlDbType.Char, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") },
|
||||
{ (int)SqlDbType.VarChar, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") },
|
||||
{ (int)SqlDbType.Text, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") },
|
||||
{ (int)SqlDbType.NChar, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") },
|
||||
{ (int)SqlDbType.NVarChar, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") },
|
||||
{ (int)SqlDbType.NText, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") },
|
||||
|
||||
{ (int)SqlDbType.UniqueIdentifier, ("(Guid?)", "Guid.Parse({0})", "{0}.ToString()", "Guid?", typeof(Guid), typeof(Guid?), "{0}.Value", "GetGuid") },
|
||||
};
|
||||
|
||||
public string GetCsConvert(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? (column.IsNullable ? trydc.csConvert : trydc.csConvert.Replace("?", "")) : null;
|
||||
public string GetCsParse(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csParse : null;
|
||||
public string GetCsStringify(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csStringify : null;
|
||||
public string GetCsType(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? (column.IsNullable ? trydc.csType : trydc.csType.Replace("?", "")) : null;
|
||||
public Type GetCsTypeInfo(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csTypeInfo : null;
|
||||
public string GetCsTypeValue(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csTypeValue : null;
|
||||
public string GetDataReaderMethod(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.dataReaderMethod : null;
|
||||
|
||||
public List<string> GetDatabases() {
|
||||
var sql = @" select name from sys.databases where name not in ('master','tempdb','model','msdb')";
|
||||
var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql);
|
||||
return ds.Select(a => a.FirstOrDefault()?.ToString()).ToList();
|
||||
}
|
||||
|
||||
public List<DbTableInfo> GetTablesByDatabase(params string[] database) {
|
||||
var olddatabase = "";
|
||||
using (var conn = _orm.Ado.MasterPool.Get(TimeSpan.FromSeconds(5))) {
|
||||
olddatabase = conn.Value.Database;
|
||||
}
|
||||
var dbs = database == null || database.Any() == false ? new[] { olddatabase } : database;
|
||||
var tables = new List<DbTableInfo>();
|
||||
|
||||
foreach (var db in dbs) {
|
||||
if (string.IsNullOrEmpty(db)) continue;
|
||||
|
||||
var loc1 = new List<DbTableInfo>();
|
||||
var loc2 = new Dictionary<int, DbTableInfo>();
|
||||
var loc3 = new Dictionary<int, Dictionary<string, DbColumnInfo>>();
|
||||
|
||||
var sql = $@"
|
||||
use [{db}];
|
||||
select
|
||||
a.Object_id
|
||||
,b.name 'Owner'
|
||||
,a.name 'Name'
|
||||
,c.value
|
||||
,'TABLE' type
|
||||
from sys.tables a
|
||||
inner join sys.schemas b on b.schema_id = a.schema_id
|
||||
left join sys.extended_properties AS c ON c.major_id = a.object_id AND c.minor_id = 0 AND c.name = 'MS_Description'
|
||||
where not(b.name = 'dbo' and a.name = 'sysdiagrams')
|
||||
union all
|
||||
select
|
||||
a.Object_id
|
||||
,b.name 'Owner'
|
||||
,a.name 'Name'
|
||||
,c.value
|
||||
,'VIEW' type
|
||||
from sys.views a
|
||||
inner join sys.schemas b on b.schema_id = a.schema_id
|
||||
left join sys.extended_properties AS c ON c.major_id = a.object_id AND c.minor_id = 0 AND c.name = 'MS_Description'
|
||||
union all
|
||||
select
|
||||
a.Object_id
|
||||
,b.name 'Owner'
|
||||
,a.name 'Name'
|
||||
,c.value
|
||||
,'StoreProcedure' type
|
||||
from sys.procedures a
|
||||
inner join sys.schemas b on b.schema_id = a.schema_id
|
||||
left join sys.extended_properties AS c ON c.major_id = a.object_id AND c.minor_id = 0 AND c.name = 'MS_Description'
|
||||
where a.type = 'P' and charindex('diagram', a.name) = 0
|
||||
order by type desc, b.name, a.name
|
||||
;
|
||||
use [{olddatabase}];
|
||||
";
|
||||
var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql);
|
||||
if (ds == null) return loc1;
|
||||
|
||||
var loc6 = new List<int>();
|
||||
var loc66 = new List<int>();
|
||||
foreach (object[] row in ds) {
|
||||
int object_id = int.Parse(string.Concat(row[0]));
|
||||
var owner = string.Concat(row[1]);
|
||||
var table = string.Concat(row[2]);
|
||||
var comment = string.Concat(row[3]);
|
||||
Enum.TryParse<DbTableType>(string.Concat(row[4]), out var type);
|
||||
loc2.Add(object_id, new DbTableInfo { Id = object_id.ToString(), Schema = owner, Name = table, Comment = comment, Type = type });
|
||||
loc3.Add(object_id, new Dictionary<string, DbColumnInfo>());
|
||||
switch (type) {
|
||||
case DbTableType.VIEW:
|
||||
case DbTableType.TABLE:
|
||||
loc6.Add(object_id);
|
||||
break;
|
||||
case DbTableType.StoreProcedure:
|
||||
loc66.Add(object_id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (loc6.Count == 0) return loc1;
|
||||
var loc8 = string.Join(",", loc6.Select(a => string.Concat(a)));
|
||||
var loc88 = string.Join(",", loc66.Select(a => string.Concat(a)));
|
||||
|
||||
var tsql_place = @"
|
||||
|
||||
select
|
||||
isnull(e.name,'') + '.' + isnull(d.name,'')
|
||||
,a.Object_id
|
||||
,a.name 'Column'
|
||||
,b.name 'Type'
|
||||
,case
|
||||
when b.name in ('Text', 'NText', 'Image') then -1
|
||||
when b.name in ('NChar', 'NVarchar') then a.max_length / 2
|
||||
else a.max_length end 'Length'
|
||||
,b.name + case
|
||||
when b.name in ('Char', 'VarChar', 'NChar', 'NVarChar', 'Binary', 'VarBinary') then '(' +
|
||||
case when a.max_length = -1 then 'MAX'
|
||||
when b.name in ('NChar', 'NVarchar') then cast(a.max_length / 2 as varchar)
|
||||
else cast(a.max_length as varchar) end + ')'
|
||||
when b.name in ('Numeric', 'Decimal') then '(' + cast(a.precision as varchar) + ',' + cast(a.scale as varchar) + ')'
|
||||
else '' end as 'SqlType'
|
||||
,c.value
|
||||
{0} a
|
||||
inner join sys.types b on b.user_type_id = a.user_type_id
|
||||
left join sys.extended_properties AS c ON c.major_id = a.object_id AND c.minor_id = a.column_id
|
||||
left join sys.tables d on d.object_id = a.object_id
|
||||
left join sys.schemas e on e.schema_id = d.schema_id
|
||||
where a.object_id in ({1})
|
||||
";
|
||||
sql = string.Format(tsql_place, @"
|
||||
,a.is_nullable 'IsNullable'
|
||||
,a.is_identity 'IsIdentity'
|
||||
from sys.columns", loc8);
|
||||
if (loc88.Length > 0) {
|
||||
sql += "union all" +
|
||||
string.Format(tsql_place.Replace(
|
||||
"left join sys.extended_properties AS c ON c.major_id = a.object_id AND c.minor_id = a.column_id",
|
||||
"left join sys.extended_properties AS c ON c.major_id = a.object_id AND c.minor_id = a.parameter_id"), @"
|
||||
,cast(0 as bit) 'IsNullable'
|
||||
,a.is_output 'IsIdentity'
|
||||
from sys.parameters", loc88);
|
||||
}
|
||||
sql = $"use [{db}];{sql};use [{olddatabase}]; ";
|
||||
ds = _orm.Ado.ExecuteArray(CommandType.Text, sql);
|
||||
if (ds == null) return loc1;
|
||||
|
||||
foreach (object[] row in ds) {
|
||||
var table_id = string.Concat(row[0]);
|
||||
var object_id = int.Parse(string.Concat(row[1]));
|
||||
var column = string.Concat(row[2]);
|
||||
var type = string.Concat(row[3]);
|
||||
var max_length = int.Parse(string.Concat(row[4]));
|
||||
var sqlType = string.Concat(row[5]);
|
||||
var comment = string.Concat(row[6]);
|
||||
var is_nullable = bool.Parse(string.Concat(row[7]));
|
||||
var is_identity = bool.Parse(string.Concat(row[8]));
|
||||
if (max_length == 0) max_length = -1;
|
||||
|
||||
loc3[object_id].Add(column, new DbColumnInfo {
|
||||
Name = column,
|
||||
MaxLength = max_length,
|
||||
IsIdentity = is_identity,
|
||||
IsNullable = is_nullable,
|
||||
IsPrimary = false,
|
||||
DbTypeText = type,
|
||||
DbTypeTextFull = sqlType,
|
||||
Table = loc2[object_id],
|
||||
Coment = comment
|
||||
});
|
||||
loc3[object_id][column].DbType = this.GetDbType(loc3[object_id][column]);
|
||||
loc3[object_id][column].CsType = this.GetCsTypeInfo(loc3[object_id][column]);
|
||||
}
|
||||
|
||||
sql = $@"
|
||||
use [{db}];
|
||||
select
|
||||
a.object_id 'Object_id'
|
||||
,c.name 'Column'
|
||||
,d.name 'Index_id'
|
||||
,b.is_unique 'IsUnique'
|
||||
,b.is_primary_key 'IsPrimaryKey'
|
||||
,cast(case when b.type_desc = 'CLUSTERED' then 1 else 0 end as bit) 'IsClustered'
|
||||
,case when a.is_descending_key = 1 then 2 when a.is_descending_key = 0 then 1 else 0 end 'IsDesc'
|
||||
from sys.index_columns a
|
||||
inner join sys.indexes b on b.object_id = a.object_id and b.index_id = a.index_id
|
||||
left join sys.columns c on c.object_id = a.object_id and c.column_id = a.column_id
|
||||
left join sys.key_constraints d on d.parent_object_id = b.object_id and d.unique_index_id = b.index_id
|
||||
where a.object_id in ({loc8})
|
||||
;
|
||||
use [{olddatabase}];
|
||||
";
|
||||
ds = _orm.Ado.ExecuteArray(CommandType.Text, sql);
|
||||
if (ds == null) return loc1;
|
||||
|
||||
var indexColumns = new Dictionary<int, Dictionary<string, List<DbColumnInfo>>>();
|
||||
var uniqueColumns = new Dictionary<int, Dictionary<string, List<DbColumnInfo>>>();
|
||||
foreach (object[] row in ds) {
|
||||
int object_id = int.Parse(string.Concat(row[0]));
|
||||
string column = string.Concat(row[1]);
|
||||
string index_id = string.Concat(row[2]);
|
||||
bool is_unique = bool.Parse(string.Concat(row[3]));
|
||||
bool is_primary_key = bool.Parse(string.Concat(row[4]));
|
||||
bool is_clustered = bool.Parse(string.Concat(row[5]));
|
||||
int is_desc = int.Parse(string.Concat(row[6]));
|
||||
|
||||
if (loc3.ContainsKey(object_id) == false || loc3[object_id].ContainsKey(column) == false) continue;
|
||||
DbColumnInfo loc9 = loc3[object_id][column];
|
||||
if (loc9.IsPrimary == false && is_primary_key) loc9.IsPrimary = is_primary_key;
|
||||
|
||||
Dictionary<string, List<DbColumnInfo>> loc10 = null;
|
||||
List<DbColumnInfo> loc11 = null;
|
||||
if (!indexColumns.TryGetValue(object_id, out loc10))
|
||||
indexColumns.Add(object_id, loc10 = new Dictionary<string, List<DbColumnInfo>>());
|
||||
if (!loc10.TryGetValue(index_id, out loc11))
|
||||
loc10.Add(index_id, loc11 = new List<DbColumnInfo>());
|
||||
loc11.Add(loc9);
|
||||
if (is_unique && !is_primary_key) {
|
||||
if (!uniqueColumns.TryGetValue(object_id, out loc10))
|
||||
uniqueColumns.Add(object_id, loc10 = new Dictionary<string, List<DbColumnInfo>>());
|
||||
if (!loc10.TryGetValue(index_id, out loc11))
|
||||
loc10.Add(index_id, loc11 = new List<DbColumnInfo>());
|
||||
loc11.Add(loc9);
|
||||
}
|
||||
}
|
||||
foreach (var object_id in indexColumns.Keys) {
|
||||
foreach (var column in indexColumns[object_id])
|
||||
loc2[object_id].IndexesDict.Add(column.Key, column.Value);
|
||||
}
|
||||
foreach (var object_id in uniqueColumns.Keys) {
|
||||
foreach (var column in uniqueColumns[object_id]) {
|
||||
column.Value.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
|
||||
loc2[object_id].UniquesDict.Add(column.Key, column.Value);
|
||||
}
|
||||
}
|
||||
|
||||
sql = $@"
|
||||
use [{db}];
|
||||
select
|
||||
b.object_id 'Object_id'
|
||||
,c.name 'Column'
|
||||
,e.name 'FKId'
|
||||
,a.referenced_object_id
|
||||
,cast(1 as bit) 'IsForeignKey'
|
||||
,d.name 'Referenced_Column'
|
||||
,null 'Referenced_Sln'
|
||||
,null 'Referenced_Table'
|
||||
from sys.foreign_key_columns a
|
||||
inner join sys.tables b on b.object_id = a.parent_object_id
|
||||
inner join sys.columns c on c.object_id = a.parent_object_id and c.column_id = a.parent_column_id
|
||||
inner join sys.columns d on d.object_id = a.referenced_object_id and d.column_id = a.referenced_column_id
|
||||
left join sys.foreign_keys e on e.object_id = a.constraint_object_id
|
||||
where b.object_id in ({loc8})
|
||||
;
|
||||
use [{olddatabase}];
|
||||
";
|
||||
ds = _orm.Ado.ExecuteArray(CommandType.Text, sql);
|
||||
if (ds == null) return loc1;
|
||||
|
||||
var fkColumns = new Dictionary<int, Dictionary<string, DbForeignInfo>>();
|
||||
foreach (object[] row in ds) {
|
||||
int object_id, referenced_object_id;
|
||||
int.TryParse(string.Concat(row[0]), out object_id);
|
||||
var column = string.Concat(row[1]);
|
||||
string fk_id = string.Concat(row[2]);
|
||||
int.TryParse(string.Concat(row[3]), out referenced_object_id);
|
||||
var is_foreign_key = bool.Parse(string.Concat(row[4]));
|
||||
var referenced_column = string.Concat(row[5]);
|
||||
var referenced_db = string.Concat(row[6]);
|
||||
var referenced_table = string.Concat(row[7]);
|
||||
DbColumnInfo loc9 = loc3[object_id][column];
|
||||
DbTableInfo loc10 = null;
|
||||
DbColumnInfo loc11 = null;
|
||||
bool isThisSln = referenced_object_id != 0;
|
||||
|
||||
if (isThisSln) {
|
||||
loc10 = loc2[referenced_object_id];
|
||||
loc11 = loc3[referenced_object_id][referenced_column];
|
||||
} else {
|
||||
|
||||
}
|
||||
Dictionary<string, DbForeignInfo> loc12 = null;
|
||||
DbForeignInfo loc13 = null;
|
||||
if (!fkColumns.TryGetValue(object_id, out loc12))
|
||||
fkColumns.Add(object_id, loc12 = new Dictionary<string, DbForeignInfo>());
|
||||
if (!loc12.TryGetValue(fk_id, out loc13))
|
||||
loc12.Add(fk_id, loc13 = new DbForeignInfo { Table = loc2[object_id], ReferencedTable = loc10 });
|
||||
loc13.Columns.Add(loc9);
|
||||
loc13.ReferencedColumns.Add(loc11);
|
||||
}
|
||||
foreach (var table_id in fkColumns.Keys)
|
||||
foreach (var fk in fkColumns[table_id])
|
||||
loc2[table_id].ForeignsDict.Add(fk.Key, fk.Value);
|
||||
|
||||
foreach (var table_id in loc3.Keys) {
|
||||
foreach (var loc5 in loc3[table_id].Values) {
|
||||
loc2[table_id].Columns.Add(loc5);
|
||||
if (loc5.IsIdentity) loc2[table_id].Identitys.Add(loc5);
|
||||
if (loc5.IsPrimary) loc2[table_id].Primarys.Add(loc5);
|
||||
}
|
||||
}
|
||||
foreach (var loc4 in loc2.Values) {
|
||||
if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0) {
|
||||
foreach (var loc5 in loc4.UniquesDict.First().Value) {
|
||||
loc5.IsPrimary = true;
|
||||
loc4.Primarys.Add(loc5);
|
||||
}
|
||||
}
|
||||
loc4.Primarys.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
|
||||
loc4.Columns.Sort((c1, c2) => {
|
||||
int compare = c2.IsPrimary.CompareTo(c1.IsPrimary);
|
||||
if (compare == 0) {
|
||||
bool b1 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c1.Name).Any()).Any();
|
||||
bool b2 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c2.Name).Any()).Any();
|
||||
compare = b2.CompareTo(b1);
|
||||
}
|
||||
if (compare == 0) compare = c1.Name.CompareTo(c2.Name);
|
||||
return compare;
|
||||
});
|
||||
loc1.Add(loc4);
|
||||
}
|
||||
loc1.Sort((t1, t2) => {
|
||||
var ret = t1.Schema.CompareTo(t2.Schema);
|
||||
if (ret == 0) ret = t1.Name.CompareTo(t2.Name);
|
||||
return ret;
|
||||
});
|
||||
|
||||
loc2.Clear();
|
||||
loc3.Clear();
|
||||
tables.AddRange(loc1);
|
||||
}
|
||||
return tables;
|
||||
}
|
||||
|
||||
public List<DbEnumInfo> GetEnumsByDatabase(params string[] database) {
|
||||
return new List<DbEnumInfo>();
|
||||
}
|
||||
}
|
||||
}
|
383
Providers/FreeSql.Provider.SqlServer/SqlServerExpression.cs
Normal file
383
Providers/FreeSql.Provider.SqlServer/SqlServerExpression.cs
Normal file
@ -0,0 +1,383 @@
|
||||
using FreeSql.Internal;
|
||||
using FreeSql.Internal.Model;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Text;
|
||||
|
||||
namespace FreeSql.SqlServer {
|
||||
class SqlServerExpression : CommonExpression {
|
||||
|
||||
public SqlServerExpression(CommonUtils common) : base(common) { }
|
||||
|
||||
public override string ExpressionLambdaToSqlOther(Expression exp, ExpTSC tsc) {
|
||||
Func<Expression, string> getExp = exparg => ExpressionLambdaToSql(exparg, tsc);
|
||||
switch (exp.NodeType) {
|
||||
case ExpressionType.Convert:
|
||||
var operandExp = (exp as UnaryExpression)?.Operand;
|
||||
var gentype = exp.Type.NullableTypeOrThis();
|
||||
if (gentype != operandExp.Type.NullableTypeOrThis()) {
|
||||
switch (gentype.ToString()) {
|
||||
case "System.Boolean": return $"(cast({getExp(operandExp)} as varchar) not in ('0','false'))";
|
||||
case "System.Byte": return $"cast({getExp(operandExp)} as tinyint)";
|
||||
case "System.Char": return $"substring(cast({getExp(operandExp)} as nvarchar),1,1)";
|
||||
case "System.DateTime": return $"cast({getExp(operandExp)} as datetime)";
|
||||
case "System.Decimal": return $"cast({getExp(operandExp)} as decimal(36,18))";
|
||||
case "System.Double": return $"cast({getExp(operandExp)} as decimal(32,16))";
|
||||
case "System.Int16": return $"cast({getExp(operandExp)} as smallint)";
|
||||
case "System.Int32": return $"cast({getExp(operandExp)} as int)";
|
||||
case "System.Int64": return $"cast({getExp(operandExp)} as bigint)";
|
||||
case "System.SByte": return $"cast({getExp(operandExp)} as tinyint)";
|
||||
case "System.Single": return $"cast({getExp(operandExp)} as decimal(14,7))";
|
||||
case "System.String": return operandExp.Type.NullableTypeOrThis() == typeof(Guid) ? $"cast({getExp(operandExp)} as varchar(36))" : $"cast({getExp(operandExp)} as nvarchar)";
|
||||
case "System.UInt16": return $"cast({getExp(operandExp)} as smallint)";
|
||||
case "System.UInt32": return $"cast({getExp(operandExp)} as int)";
|
||||
case "System.UInt64": return $"cast({getExp(operandExp)} as bigint)";
|
||||
case "System.Guid": return $"cast({getExp(operandExp)} as uniqueidentifier)";
|
||||
}
|
||||
}
|
||||
break;
|
||||
case ExpressionType.Call:
|
||||
var callExp = exp as MethodCallExpression;
|
||||
|
||||
switch(callExp.Method.Name) {
|
||||
case "Parse":
|
||||
case "TryParse":
|
||||
switch (callExp.Method.DeclaringType.NullableTypeOrThis().ToString()) {
|
||||
case "System.Boolean": return $"(cast({getExp(callExp.Arguments[0])} as varchar) not in ('0','false'))";
|
||||
case "System.Byte": return $"cast({getExp(callExp.Arguments[0])} as tinyint)";
|
||||
case "System.Char": return $"substring(cast({getExp(callExp.Arguments[0])} as nvarchar),1,1)";
|
||||
case "System.DateTime": return $"cast({getExp(callExp.Arguments[0])} as datetime)";
|
||||
case "System.Decimal": return $"cast({getExp(callExp.Arguments[0])} as decimal(36,18))";
|
||||
case "System.Double": return $"cast({getExp(callExp.Arguments[0])} as decimal(32,16))";
|
||||
case "System.Int16": return $"cast({getExp(callExp.Arguments[0])} as smallint)";
|
||||
case "System.Int32": return $"cast({getExp(callExp.Arguments[0])} as int)";
|
||||
case "System.Int64": return $"cast({getExp(callExp.Arguments[0])} as bigint)";
|
||||
case "System.SByte": return $"cast({getExp(callExp.Arguments[0])} as tinyint)";
|
||||
case "System.Single": return $"cast({getExp(callExp.Arguments[0])} as decimal(14,7))";
|
||||
case "System.UInt16": return $"cast({getExp(callExp.Arguments[0])} as smallint)";
|
||||
case "System.UInt32": return $"cast({getExp(callExp.Arguments[0])} as int)";
|
||||
case "System.UInt64": return $"cast({getExp(callExp.Arguments[0])} as bigint)";
|
||||
case "System.Guid": return $"cast({getExp(callExp.Arguments[0])} as uniqueidentifier)";
|
||||
}
|
||||
break;
|
||||
case "NewGuid":
|
||||
switch (callExp.Method.DeclaringType.NullableTypeOrThis().ToString()) {
|
||||
case "System.Guid": return $"newid()";
|
||||
}
|
||||
break;
|
||||
case "Next":
|
||||
if (callExp.Object?.Type == typeof(Random)) return "cast(rand()*1000000000 as int)";
|
||||
break;
|
||||
case "NextDouble":
|
||||
if (callExp.Object?.Type == typeof(Random)) return "rand()";
|
||||
break;
|
||||
case "Random":
|
||||
if (callExp.Method.DeclaringType.IsNumberType()) return "rand()";
|
||||
break;
|
||||
case "ToString":
|
||||
if (callExp.Object != null) return callExp.Object.Type.NullableTypeOrThis() == typeof(Guid) ? $"cast({getExp(callExp.Object)} as varchar(36))" : $"cast({getExp(callExp.Object)} as nvarchar)";
|
||||
break;
|
||||
}
|
||||
|
||||
var objExp = callExp.Object;
|
||||
var objType = objExp?.Type;
|
||||
if (objType?.FullName == "System.Byte[]") return null;
|
||||
|
||||
var argIndex = 0;
|
||||
if (objType == null && callExp.Method.DeclaringType == typeof(Enumerable)) {
|
||||
objExp = callExp.Arguments.FirstOrDefault();
|
||||
objType = objExp?.Type;
|
||||
argIndex++;
|
||||
}
|
||||
if (objType == null) objType = callExp.Method.DeclaringType;
|
||||
if (objType != null || objType.IsArray || typeof(IList).IsAssignableFrom(callExp.Method.DeclaringType)) {
|
||||
var left = objExp == null ? null : getExp(objExp);
|
||||
switch (callExp.Method.Name) {
|
||||
case "Contains":
|
||||
//判断 in
|
||||
return $"({getExp(callExp.Arguments[argIndex])}) in {left}";
|
||||
}
|
||||
}
|
||||
break;
|
||||
case ExpressionType.NewArrayInit:
|
||||
var arrExp = exp as NewArrayExpression;
|
||||
var arrSb = new StringBuilder();
|
||||
arrSb.Append("(");
|
||||
for (var a = 0; a < arrExp.Expressions.Count; a++) {
|
||||
if (a > 0) arrSb.Append(",");
|
||||
arrSb.Append(getExp(arrExp.Expressions[a]));
|
||||
}
|
||||
if (arrSb.Length == 1) arrSb.Append("NULL");
|
||||
return arrSb.Append(")").ToString();
|
||||
case ExpressionType.ListInit:
|
||||
var listExp = exp as ListInitExpression;
|
||||
var listSb = new StringBuilder();
|
||||
listSb.Append("(");
|
||||
for (var a = 0; a < listExp.Initializers.Count; a++) {
|
||||
if (listExp.Initializers[a].Arguments.Any() == false) continue;
|
||||
if (a > 0) listSb.Append(",");
|
||||
listSb.Append(getExp(listExp.Initializers[a].Arguments.FirstOrDefault()));
|
||||
}
|
||||
if (listSb.Length == 1) listSb.Append("NULL");
|
||||
return listSb.Append(")").ToString();
|
||||
case ExpressionType.New:
|
||||
var newExp = exp as NewExpression;
|
||||
if (typeof(IList).IsAssignableFrom(newExp.Type)) {
|
||||
if (newExp.Arguments.Count == 0) return "(NULL)";
|
||||
if (typeof(IEnumerable).IsAssignableFrom(newExp.Arguments[0].Type) == false) return "(NULL)";
|
||||
return getExp(newExp.Arguments[0]);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public override string ExpressionLambdaToSqlMemberAccessString(MemberExpression exp, ExpTSC tsc) {
|
||||
if (exp.Expression == null) {
|
||||
switch (exp.Member.Name) {
|
||||
case "Empty": return "''";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
var left = ExpressionLambdaToSql(exp.Expression, tsc);
|
||||
switch (exp.Member.Name) {
|
||||
case "Length": return $"len({left})";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public override string ExpressionLambdaToSqlMemberAccessDateTime(MemberExpression exp, ExpTSC tsc) {
|
||||
if (exp.Expression == null) {
|
||||
switch (exp.Member.Name) {
|
||||
case "Now": return "getdate()";
|
||||
case "UtcNow": return "getutcdate()";
|
||||
case "Today": return "convert(char(10),getdate(),120)";
|
||||
case "MinValue": return "'1753/1/1 0:00:00'";
|
||||
case "MaxValue": return "'9999/12/31 23:59:59'";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
var left = ExpressionLambdaToSql(exp.Expression, tsc);
|
||||
switch (exp.Member.Name) {
|
||||
case "Date": return $"convert(char(10),{left},120)";
|
||||
case "TimeOfDay": return $"datediff(second, convert(char(10),{left},120), {left})";
|
||||
case "DayOfWeek": return $"(datepart(weekday, {left})-1)";
|
||||
case "Day": return $"datepart(day, {left})";
|
||||
case "DayOfYear": return $"datepart(dayofyear, {left})";
|
||||
case "Month": return $"datepart(month, {left})";
|
||||
case "Year": return $"datepart(year, {left})";
|
||||
case "Hour": return $"datepart(hour, {left})";
|
||||
case "Minute": return $"datepart(minute, {left})";
|
||||
case "Second": return $"datepart(second, {left})";
|
||||
case "Millisecond": return $"(datepart(millisecond, {left})/1000)";
|
||||
case "Ticks": return $"(cast(datediff(second, '1970-1-1', {left}) as bigint)*10000000+621355968000000000)";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public override string ExpressionLambdaToSqlMemberAccessTimeSpan(MemberExpression exp, ExpTSC tsc) {
|
||||
if (exp.Expression == null) {
|
||||
switch (exp.Member.Name) {
|
||||
case "Zero": return "0";
|
||||
case "MinValue": return "-922337203685477580"; //微秒 Ticks / 10
|
||||
case "MaxValue": return "922337203685477580";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
var left = ExpressionLambdaToSql(exp.Expression, tsc);
|
||||
switch (exp.Member.Name) {
|
||||
case "Days": return $"floor(({left})/{60 * 60 * 24})";
|
||||
case "Hours": return $"floor(({left})/{60 * 60}%24)";
|
||||
case "Milliseconds": return $"(cast({left} as bigint)*1000)";
|
||||
case "Minutes": return $"floor(({left})/60%60)";
|
||||
case "Seconds": return $"(({left})%60)";
|
||||
case "Ticks": return $"(cast({left} as bigint)*10000000)";
|
||||
case "TotalDays": return $"(({left})/{60 * 60 * 24})";
|
||||
case "TotalHours": return $"(({left})/{60 * 60})";
|
||||
case "TotalMilliseconds": return $"(cast({left} as bigint)*1000)";
|
||||
case "TotalMinutes": return $"(({left})/60)";
|
||||
case "TotalSeconds": return $"({left})";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, ExpTSC tsc) {
|
||||
Func<Expression, string> getExp = exparg => ExpressionLambdaToSql(exparg, tsc);
|
||||
if (exp.Object == null) {
|
||||
switch (exp.Method.Name) {
|
||||
case "IsNullOrEmpty":
|
||||
var arg1 = getExp(exp.Arguments[0]);
|
||||
return $"({arg1} is null or {arg1} = '')";
|
||||
case "Concat":
|
||||
return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), exp.Arguments.Select(a => a.Type).ToArray());
|
||||
}
|
||||
} else {
|
||||
var left = getExp(exp.Object);
|
||||
switch (exp.Method.Name) {
|
||||
case "StartsWith":
|
||||
case "EndsWith":
|
||||
case "Contains":
|
||||
var args0Value = getExp(exp.Arguments[0]);
|
||||
if (args0Value == "NULL") return $"({left}) IS NULL";
|
||||
if (exp.Method.Name == "StartsWith") return $"({left}) LIKE {(args0Value.EndsWith("'") ? args0Value.Insert(args0Value.Length - 1, "%") : $"(cast({args0Value} as nvarchar)+'%')")}";
|
||||
if (exp.Method.Name == "EndsWith") return $"({left}) LIKE {(args0Value.StartsWith("'") ? args0Value.Insert(1, "%") : $"('%'+cast({args0Value} as nvarchar))")}";
|
||||
if (args0Value.StartsWith("'") && args0Value.EndsWith("'")) return $"({left}) LIKE {args0Value.Insert(1, "%").Insert(args0Value.Length, "%")}";
|
||||
return $"({left}) LIKE ('%'+cast({args0Value} as nvarchar)+'%')";
|
||||
case "ToLower": return $"lower({left})";
|
||||
case "ToUpper": return $"upper({left})";
|
||||
case "Substring":
|
||||
var substrArgs1 = getExp(exp.Arguments[0]);
|
||||
if (long.TryParse(substrArgs1, out var testtrylng1)) substrArgs1 = (testtrylng1 + 1).ToString();
|
||||
else substrArgs1 += "+1";
|
||||
if (exp.Arguments.Count == 1) return $"left({left}, {substrArgs1})";
|
||||
return $"substring({left}, {substrArgs1}, {getExp(exp.Arguments[1])})";
|
||||
case "IndexOf":
|
||||
var indexOfFindStr = getExp(exp.Arguments[0]);
|
||||
if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") {
|
||||
var locateArgs1 = getExp(exp.Arguments[1]);
|
||||
if (long.TryParse(locateArgs1, out var testtrylng2)) locateArgs1 = (testtrylng2 + 1).ToString();
|
||||
else locateArgs1 += "+1";
|
||||
return $"(charindex({left}, {indexOfFindStr}, {locateArgs1})-1)";
|
||||
}
|
||||
return $"(charindex({left}, {indexOfFindStr})-1)";
|
||||
case "PadLeft":
|
||||
if (exp.Arguments.Count == 1) return $"lpad({left}, {getExp(exp.Arguments[0])})";
|
||||
return $"lpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
|
||||
case "PadRight":
|
||||
if (exp.Arguments.Count == 1) return $"rpad({left}, {getExp(exp.Arguments[0])})";
|
||||
return $"rpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
|
||||
case "Trim": return $"ltrim(rtrim({left}))";
|
||||
case "TrimStart": return $"ltrim({left})";
|
||||
case "TrimEnd": return $"rtrim({left})";
|
||||
case "Replace": return $"replace({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
|
||||
case "CompareTo": return $"({left} - {getExp(exp.Arguments[0])})";
|
||||
case "Equals": return $"({left} = {getExp(exp.Arguments[0])})";
|
||||
}
|
||||
}
|
||||
throw new Exception($"SqlServerExpression 未实现函数表达式 {exp} 解析");
|
||||
}
|
||||
public override string ExpressionLambdaToSqlCallMath(MethodCallExpression exp, ExpTSC tsc) {
|
||||
Func<Expression, string> getExp = exparg => ExpressionLambdaToSql(exparg, tsc);
|
||||
switch (exp.Method.Name) {
|
||||
case "Abs": return $"abs({getExp(exp.Arguments[0])})";
|
||||
case "Sign": return $"sign({getExp(exp.Arguments[0])})";
|
||||
case "Floor": return $"floor({getExp(exp.Arguments[0])})";
|
||||
case "Ceiling": return $"ceiling({getExp(exp.Arguments[0])})";
|
||||
case "Round":
|
||||
if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") return $"round({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
|
||||
return $"round({getExp(exp.Arguments[0])}, 0)";
|
||||
case "Exp": return $"exp({getExp(exp.Arguments[0])})";
|
||||
case "Log": return $"log({getExp(exp.Arguments[0])})";
|
||||
case "Log10": return $"log10({getExp(exp.Arguments[0])})";
|
||||
case "Pow": return $"power({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
|
||||
case "Sqrt": return $"sqrt({getExp(exp.Arguments[0])})";
|
||||
case "Cos": return $"cos({getExp(exp.Arguments[0])})";
|
||||
case "Sin": return $"sin({getExp(exp.Arguments[0])})";
|
||||
case "Tan": return $"tan({getExp(exp.Arguments[0])})";
|
||||
case "Acos": return $"acos({getExp(exp.Arguments[0])})";
|
||||
case "Asin": return $"asin({getExp(exp.Arguments[0])})";
|
||||
case "Atan": return $"atan({getExp(exp.Arguments[0])})";
|
||||
case "Atan2": return $"atan2({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
|
||||
case "Truncate": return $"floor({getExp(exp.Arguments[0])})";
|
||||
}
|
||||
throw new Exception($"SqlServerExpression 未实现函数表达式 {exp} 解析");
|
||||
}
|
||||
public override string ExpressionLambdaToSqlCallDateTime(MethodCallExpression exp, ExpTSC tsc) {
|
||||
Func<Expression, string> getExp = exparg => ExpressionLambdaToSql(exparg, tsc);
|
||||
if (exp.Object == null) {
|
||||
switch (exp.Method.Name) {
|
||||
case "Compare": return $"({getExp(exp.Arguments[0])} - ({getExp(exp.Arguments[1])}))";
|
||||
case "DaysInMonth": return $"datepart(day, dateadd(day, -1, dateadd(month, 1, cast({getExp(exp.Arguments[0])} as varchar) + '-' + cast({getExp(exp.Arguments[1])} as varchar) + '-1')))";
|
||||
case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})";
|
||||
|
||||
case "IsLeapYear":
|
||||
var isLeapYearArgs1 = getExp(exp.Arguments[0]);
|
||||
return $"(({isLeapYearArgs1})%4=0 AND ({isLeapYearArgs1})%100<>0 OR ({isLeapYearArgs1})%400=0)";
|
||||
|
||||
case "Parse": return $"cast({getExp(exp.Arguments[0])} as datetime)";
|
||||
case "ParseExact":
|
||||
case "TryParse":
|
||||
case "TryParseExact": return $"cast({getExp(exp.Arguments[0])} as datetime)";
|
||||
}
|
||||
} else {
|
||||
var left = getExp(exp.Object);
|
||||
var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]);
|
||||
switch (exp.Method.Name) {
|
||||
case "Add": return $"dateadd(second, {args1}, {left})";
|
||||
case "AddDays": return $"dateadd(day, {args1}, {left})";
|
||||
case "AddHours": return $"dateadd(hour, {args1}, {left})";
|
||||
case "AddMilliseconds": return $"dateadd(second, ({args1})/1000, {left})";
|
||||
case "AddMinutes": return $"dateadd(minute, {args1}, {left})";
|
||||
case "AddMonths": return $"dateadd(month, {args1}, {left})";
|
||||
case "AddSeconds": return $"dateadd(second, {args1}, {left})";
|
||||
case "AddTicks": return $"dateadd(second, ({args1})/10000000, {left})";
|
||||
case "AddYears": return $"dateadd(year, {args1}, {left})";
|
||||
case "Subtract":
|
||||
switch ((exp.Arguments[0].Type.IsNullableType() ? exp.Arguments[0].Type.GenericTypeArguments.FirstOrDefault() : exp.Arguments[0].Type).FullName) {
|
||||
case "System.DateTime": return $"datediff(second, {args1}, {left})";
|
||||
case "System.TimeSpan": return $"dateadd(second, {args1}*-1, {left})";
|
||||
}
|
||||
break;
|
||||
case "Equals": return $"({left} = {getExp(exp.Arguments[0])})";
|
||||
case "CompareTo": return $"datediff(second,{getExp(exp.Arguments[0])},{left})";
|
||||
case "ToString": return $"convert(varchar, {left}, 121)";
|
||||
}
|
||||
}
|
||||
throw new Exception($"SqlServerExpression 未实现函数表达式 {exp} 解析");
|
||||
}
|
||||
public override string ExpressionLambdaToSqlCallTimeSpan(MethodCallExpression exp, ExpTSC tsc) {
|
||||
Func<Expression, string> getExp = exparg => ExpressionLambdaToSql(exparg, tsc);
|
||||
if (exp.Object == null) {
|
||||
switch (exp.Method.Name) {
|
||||
case "Compare": return $"({getExp(exp.Arguments[0])}-({getExp(exp.Arguments[1])}))";
|
||||
case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})";
|
||||
case "FromDays": return $"(({getExp(exp.Arguments[0])})*{60 * 60 * 24})";
|
||||
case "FromHours": return $"(({getExp(exp.Arguments[0])})*{60 * 60})";
|
||||
case "FromMilliseconds": return $"(({getExp(exp.Arguments[0])})/1000)";
|
||||
case "FromMinutes": return $"(({getExp(exp.Arguments[0])})*60)";
|
||||
case "FromSeconds": return $"({getExp(exp.Arguments[0])})";
|
||||
case "FromTicks": return $"(({getExp(exp.Arguments[0])})/10000000)";
|
||||
case "Parse": return $"cast({getExp(exp.Arguments[0])} as bigint)";
|
||||
case "ParseExact":
|
||||
case "TryParse":
|
||||
case "TryParseExact": return $"cast({getExp(exp.Arguments[0])} as bigint)";
|
||||
}
|
||||
} else {
|
||||
var left = getExp(exp.Object);
|
||||
var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]);
|
||||
switch (exp.Method.Name) {
|
||||
case "Add": return $"({left}+{args1})";
|
||||
case "Subtract": return $"({left}-({args1}))";
|
||||
case "Equals": return $"({left} = {getExp(exp.Arguments[0])})";
|
||||
case "CompareTo": return $"({left}-({getExp(exp.Arguments[0])}))";
|
||||
case "ToString": return $"cast({left} as varchar)";
|
||||
}
|
||||
}
|
||||
throw new Exception($"SqlServerExpression 未实现函数表达式 {exp} 解析");
|
||||
}
|
||||
public override string ExpressionLambdaToSqlCallConvert(MethodCallExpression exp, ExpTSC tsc) {
|
||||
Func<Expression, string> getExp = exparg => ExpressionLambdaToSql(exparg, tsc);
|
||||
if (exp.Object == null) {
|
||||
switch (exp.Method.Name) {
|
||||
case "ToBoolean": return $"(cast({getExp(exp.Arguments[0])} as varchar) not in ('0','false'))";
|
||||
case "ToByte": return $"cast({getExp(exp.Arguments[0])} as tinyint)";
|
||||
case "ToChar": return $"substring(cast({getExp(exp.Arguments[0])} as nvarchar),1,1)";
|
||||
case "ToDateTime": return $"cast({getExp(exp.Arguments[0])} as datetime)";
|
||||
case "ToDecimal": return $"cast({getExp(exp.Arguments[0])} as decimal(36,18))";
|
||||
case "ToDouble": return $"cast({getExp(exp.Arguments[0])} as decimal(32,16))";
|
||||
case "ToInt16": return $"cast({getExp(exp.Arguments[0])} as smallint)";
|
||||
case "ToInt32": return $"cast({getExp(exp.Arguments[0])} as int)";
|
||||
case "ToInt64": return $"cast({getExp(exp.Arguments[0])} as bigint)";
|
||||
case "ToSByte": return $"cast({getExp(exp.Arguments[0])} as tinyint)";
|
||||
case "ToSingle": return $"cast({getExp(exp.Arguments[0])} as decimal(14,7))";
|
||||
case "ToString": return exp.Arguments[0].Type.NullableTypeOrThis() == typeof(Guid) ? $"cast({getExp(exp.Arguments[0])} as varchar(36))" : $"cast({getExp(exp.Arguments[0])} as nvarchar)";
|
||||
case "ToUInt16": return $"cast({getExp(exp.Arguments[0])} as smallint)";
|
||||
case "ToUInt32": return $"cast({getExp(exp.Arguments[0])} as int)";
|
||||
case "ToUInt64": return $"cast({getExp(exp.Arguments[0])} as bigint)";
|
||||
}
|
||||
}
|
||||
throw new Exception($"SqlServerExpression 未实现函数表达式 {exp} 解析");
|
||||
}
|
||||
}
|
||||
}
|
11
Providers/FreeSql.Provider.SqlServer/SqlServerExtensions.cs
Normal file
11
Providers/FreeSql.Provider.SqlServer/SqlServerExtensions.cs
Normal file
@ -0,0 +1,11 @@
|
||||
public static partial class FreeSqlGlobalExtensions {
|
||||
|
||||
/// <summary>
|
||||
/// 特殊处理类似 string.Format 的使用方法,防止注入,以及 IS NULL 转换
|
||||
/// </summary>
|
||||
/// <param name="that"></param>
|
||||
/// <param name="args"></param>
|
||||
/// <returns></returns>
|
||||
public static string FormatSqlServer(this string that, params object[] args) => _sqlserverAdo.Addslashes(that, args);
|
||||
static FreeSql.SqlServer.SqlServerAdo _sqlserverAdo = new FreeSql.SqlServer.SqlServerAdo();
|
||||
}
|
61
Providers/FreeSql.Provider.SqlServer/SqlServerProvider.cs
Normal file
61
Providers/FreeSql.Provider.SqlServer/SqlServerProvider.cs
Normal file
@ -0,0 +1,61 @@
|
||||
using FreeSql.Internal;
|
||||
using FreeSql.Internal.CommonProvider;
|
||||
using FreeSql.SqlServer.Curd;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace FreeSql.SqlServer {
|
||||
|
||||
public class SqlServerProvider<TMark> : IFreeSql<TMark> {
|
||||
|
||||
public ISelect<T1> Select<T1>() where T1 : class => new SqlServerSelect<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression, null);
|
||||
public ISelect<T1> Select<T1>(object dywhere) where T1 : class => new SqlServerSelect<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere);
|
||||
public IInsert<T1> Insert<T1>() where T1 : class => new SqlServerInsert<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression);
|
||||
public IInsert<T1> Insert<T1>(T1 source) where T1 : class => this.Insert<T1>().AppendData(source);
|
||||
public IInsert<T1> Insert<T1>(T1[] source) where T1 : class => this.Insert<T1>().AppendData(source);
|
||||
public IInsert<T1> Insert<T1>(IEnumerable<T1> source) where T1 : class => this.Insert<T1>().AppendData(source);
|
||||
public IUpdate<T1> Update<T1>() where T1 : class => new SqlServerUpdate<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression, null);
|
||||
public IUpdate<T1> Update<T1>(object dywhere) where T1 : class => new SqlServerUpdate<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere);
|
||||
public IDelete<T1> Delete<T1>() where T1 : class => new SqlServerDelete<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression, null);
|
||||
public IDelete<T1> Delete<T1>(object dywhere) where T1 : class => new SqlServerDelete<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere);
|
||||
|
||||
public IAdo Ado { get; }
|
||||
public IAop Aop { get; }
|
||||
public ICodeFirst CodeFirst { get; }
|
||||
public IDbFirst DbFirst { get; }
|
||||
public SqlServerProvider(string masterConnectionString, string[] slaveConnectionString) {
|
||||
this.InternalCommonUtils = new SqlServerUtils(this);
|
||||
this.InternalCommonExpression = new SqlServerExpression(this.InternalCommonUtils);
|
||||
|
||||
this.Ado = new SqlServerAdo(this.InternalCommonUtils, masterConnectionString, slaveConnectionString);
|
||||
this.Aop = new AopProvider();
|
||||
|
||||
this.DbFirst = new SqlServerDbFirst(this, this.InternalCommonUtils, this.InternalCommonExpression);
|
||||
this.CodeFirst = new SqlServerCodeFirst(this, this.InternalCommonUtils, this.InternalCommonExpression);
|
||||
|
||||
if (this.Ado.MasterPool != null)
|
||||
using (var conn = this.Ado.MasterPool.Get()) {
|
||||
try {
|
||||
(this.InternalCommonUtils as SqlServerUtils).IsSelectRowNumber = int.Parse(conn.Value.ServerVersion.Split('.')[0]) <= 10;
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal CommonUtils InternalCommonUtils { get; }
|
||||
internal CommonExpression InternalCommonExpression { get; }
|
||||
|
||||
public void Transaction(Action handler) => Ado.Transaction(handler);
|
||||
|
||||
public void Transaction(Action handler, TimeSpan timeout) => Ado.Transaction(handler, timeout);
|
||||
|
||||
~SqlServerProvider() {
|
||||
this.Dispose();
|
||||
}
|
||||
bool _isdisposed = false;
|
||||
public void Dispose() {
|
||||
if (_isdisposed) return;
|
||||
(this.Ado as AdoProvider).Dispose();
|
||||
}
|
||||
}
|
||||
}
|
82
Providers/FreeSql.Provider.SqlServer/SqlServerUtils.cs
Normal file
82
Providers/FreeSql.Provider.SqlServer/SqlServerUtils.cs
Normal file
@ -0,0 +1,82 @@
|
||||
using FreeSql.Internal;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Text;
|
||||
|
||||
namespace FreeSql.SqlServer {
|
||||
|
||||
class SqlServerUtils : CommonUtils {
|
||||
public SqlServerUtils(IFreeSql orm) : base(orm) {
|
||||
}
|
||||
|
||||
public bool IsSelectRowNumber = true;
|
||||
|
||||
public override DbParameter AppendParamter(List<DbParameter> _params, string parameterName, Type type, object value) {
|
||||
if (string.IsNullOrEmpty(parameterName)) parameterName = $"p_{_params?.Count}";
|
||||
if (value?.Equals(DateTime.MinValue) == true) value = new DateTime(1970, 1, 1);
|
||||
var ret = new SqlParameter { ParameterName = QuoteParamterName(parameterName), Value = value };
|
||||
var tp = _orm.CodeFirst.GetDbInfo(type)?.type;
|
||||
if (tp != null) ret.SqlDbType = (SqlDbType)tp.Value;
|
||||
_params?.Add(ret);
|
||||
return ret;
|
||||
}
|
||||
|
||||
public override DbParameter[] GetDbParamtersByObject(string sql, object obj) =>
|
||||
Utils.GetDbParamtersByObject<SqlParameter>(sql, obj, "@", (name, type, value) => {
|
||||
if (value?.Equals(DateTime.MinValue) == true) value = new DateTime(1970, 1, 1);
|
||||
var ret = new SqlParameter { ParameterName = $"@{name}", Value = value };
|
||||
var tp = _orm.CodeFirst.GetDbInfo(type)?.type;
|
||||
if (tp != null) ret.SqlDbType = (SqlDbType)tp.Value;
|
||||
return ret;
|
||||
});
|
||||
|
||||
public override string FormatSql(string sql, params object[] args) => sql?.FormatSqlServer(args);
|
||||
public override string QuoteSqlName(string name) {
|
||||
var nametrim = name.Trim();
|
||||
if (nametrim.StartsWith("(") && nametrim.EndsWith(")"))
|
||||
return nametrim; //原生SQL
|
||||
return $"[{nametrim.TrimStart('[').TrimEnd(']').Replace(".", "].[")}]";
|
||||
}
|
||||
public override string TrimQuoteSqlName(string name) {
|
||||
var nametrim = name.Trim();
|
||||
if (nametrim.StartsWith("(") && nametrim.EndsWith(")"))
|
||||
return nametrim; //原生SQL
|
||||
return $"{nametrim.TrimStart('[').TrimEnd(']').Replace("].[", ".").Replace(".[", ".")}";
|
||||
}
|
||||
public override string QuoteParamterName(string name) => $"@{(_orm.CodeFirst.IsSyncStructureToLower ? name.ToLower() : name)}";
|
||||
public override string IsNull(string sql, object value) => $"isnull({sql}, {value})";
|
||||
public override string StringConcat(string[] objs, Type[] types) {
|
||||
var sb = new StringBuilder();
|
||||
var news = new string[objs.Length];
|
||||
for (var a = 0; a < objs.Length; a++)
|
||||
news[a] = types[a] == typeof(string) ? objs[a] : $"cast({objs[a]} as nvarchar)";
|
||||
return string.Join(" + ", news);
|
||||
}
|
||||
public override string Mod(string left, string right, Type leftType, Type rightType) => $"{left} % {right}";
|
||||
|
||||
public override string QuoteWriteParamter(Type type, string paramterName) => paramterName;
|
||||
public override string QuoteReadColumn(Type type, string columnName) => columnName;
|
||||
|
||||
public override string GetNoneParamaterSqlValue(List<DbParameter> specialParams, Type type, object value) {
|
||||
if (value == null) return "NULL";
|
||||
if (type == typeof(byte[])) {
|
||||
var bytes = value as byte[];
|
||||
var sb = new StringBuilder().Append("0x");
|
||||
foreach (var vc in bytes) {
|
||||
if (vc < 10) sb.Append("0");
|
||||
sb.Append(vc.ToString("X"));
|
||||
}
|
||||
return sb.ToString();
|
||||
} else if (type == typeof(TimeSpan) || type == typeof(TimeSpan?)) {
|
||||
var ts = (TimeSpan)value;
|
||||
value = $"{ts.Hours}:{ts.Minutes}:{ts.Seconds}.{ts.Milliseconds}";
|
||||
}
|
||||
return FormatSql("{0}", value, 1);
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user