diff --git a/Src/Asp.NetCore2/4TDSQLForOracleODBCTest/4TDSQLForOracleODBCTest.csproj b/Src/Asp.NetCore2/4TDSQLForOracleODBCTest/4TDSQLForOracleODBCTest.csproj new file mode 100644 index 0000000000000000000000000000000000000000..1907a8f65fa1933b8f046765131511315ab2faa1 --- /dev/null +++ b/Src/Asp.NetCore2/4TDSQLForOracleODBCTest/4TDSQLForOracleODBCTest.csproj @@ -0,0 +1,16 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + + + \ No newline at end of file diff --git a/Src/Asp.NetCore2/4TDSQLForOracleODBCTest/Config.cs b/Src/Asp.NetCore2/4TDSQLForOracleODBCTest/Config.cs new file mode 100644 index 0000000000000000000000000000000000000000..9f301dbbb2a312cb9e788070fa03b84edef1a86e --- /dev/null +++ b/Src/Asp.NetCore2/4TDSQLForOracleODBCTest/Config.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TDSQLForOracleODBCTest +{ + /// + /// Setting up the database name does not require you to create the database + /// 设置好数据库名不需要你去手动建库 + /// + public class Config + { + /// + /// Account have permission to create database + /// 用有建库权限的数据库账号 + /// + public static string ConnectionString = "Driver={TDSQL PostgreSQL Unicode(x64)};Server=172.19.4.37;Port=11001;Database=XIRBOC;Uid=XRFQ_APP;Pwd=xQuant.2026;ConnSettings=set search_path to XRFQ_APP;"; + /// + /// Account have permission to create database + /// 用有建库权限的数据库账号 + /// + public static string ConnectionString2 = "Driver={GBase ODBC DRIVER (64-Bit)};Host=localhost;Service=19088;Server=gbase01;Database=testdb;Protocol=onsoctcp;Uid=gbasedbt;Pwd=GBase123;Db_locale=zh_CN.utf8;Client_locale=zh_CN.utf8"; + /// + /// Account have permission to create database + /// 用有建库权限的数据库账号 + /// + public static string ConnectionString3 = "Driver={GBase ODBC DRIVER (64-Bit)};Host=localhost;Service=19088;Server=gbase01;Database=testdb;Protocol=onsoctcp;Uid=gbasedbt;Pwd=GBase123;Db_locale=zh_CN.utf8;Client_locale=zh_CN.utf8"; + } +} diff --git a/Src/Asp.NetCore2/4TDSQLForOracleODBCTest/Program.cs b/Src/Asp.NetCore2/4TDSQLForOracleODBCTest/Program.cs new file mode 100644 index 0000000000000000000000000000000000000000..0ee48f17ddaab4fa5a1a701213458a3c15101c10 --- /dev/null +++ b/Src/Asp.NetCore2/4TDSQLForOracleODBCTest/Program.cs @@ -0,0 +1,171 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using xTPLM.RFQ.Model.XRFQ_APP; + +namespace TDSQLForOracleODBCTest +{ + internal class Program + { + static void Main(string[] args) + { + Console.WriteLine(""); + Console.WriteLine("#### MasterSlave Start ####"); + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + ConnectionString = Config.ConnectionString,//Master Connection + DbType = DbType.TDSQLForOracleODBC,//Oracle 模式用这个 ,如果是MySql 模式用DbType.MySql + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + }); + //var date = DateTime.Now; + ////查询 + //var list = db.Queryable().Where(m => m.ORDER_DATE.Value.Date <= date.Date).ToList(); + + + //var list2 = db.Queryable().Where(m => m.ORDER_DATE.Value.Date <= date.Date).ToOffsetPage(1, 50); + //var item = new TRFQ_QUOTATION() + //{ + // ORDER_DATE = DateTime.Now, + // Q_STATUS = 0, + //}; + + //var item2 = new TRFQ_QUOTATION() + //{ + // ORDER_DATE = DateTime.Now, + // Q_STATUS = 0, + //}; + + //var item3 = new TRFQ_QUOTATION() + //{ + // ORDER_DATE = DateTime.Now, + // Q_STATUS = 0, + //}; + //var insertList = new List() { item, item2, item3 }; + ////新增 + //var newid = db.Insertable(insertList).ExecuteReturnIdentity(); + //item.Q_SYSID = newid; + + ////修改 + //db.Updateable().SetColumns(it => new TRFQ_QUOTATION() + //{ + // Q_STATUS = 1 + //}).Where(m => m.Q_SYSID == newid).ExecuteCommand(); + + //item.Q_STATUS = 2; + ////修改 + //db.Updateable(item).UpdateColumns(["Q_STATUS"]).ExecuteCommand(); + + //item.Q_STATUS = 3; + //List updateList = [item]; + //updateList.Add(new TRFQ_QUOTATION + //{ + // Q_SYSID = 15739, + // Q_STATUS = 4 + //}); + + List updateList = []; + updateList.Add(new TRFQ_COUNTERPARTY + { + P_SYSID = 85583, + PARTYNAME = "北京证券公司", + PARTYNAME_SHORT = "北京证券公司", + }); + updateList.Add(new TRFQ_COUNTERPARTY + { + P_SYSID = 106742, + PARTYNAME = "财通基金丰悦稳健6号单一资产管理计划", + PARTYNAME_SHORT = "财通基金丰悦稳健6号单一", + }); + updateList.Add(new TRFQ_COUNTERPARTY + { + P_SYSID = 132460, + PARTYNAME = "汇添富全天候策略1号集合资产管理计划", + PARTYNAME_SHORT = "汇添富全天候策略1号集合", + }); + updateList.Add(new TRFQ_COUNTERPARTY + { + P_SYSID = 83442, + PARTYNAME = "中国银行股份有限公司", + PARTYNAME_SHORT = "中国银行", + }); + updateList.Add(new TRFQ_COUNTERPARTY + { + P_SYSID = 83442, + PARTYNAME = "中国银行股份有限公司", + PARTYNAME_SHORT = "中国银行", + }); + updateList.Add(new TRFQ_COUNTERPARTY + { + P_SYSID = 83442, + PARTYNAME = "中国银行股份有限公司", + PARTYNAME_SHORT = "中国银行", + }); + updateList.Add(new TRFQ_COUNTERPARTY + { + P_SYSID = 83442, + PARTYNAME = "中国银行股份有限公司", + PARTYNAME_SHORT = "中国银行", + }); + updateList.Add(new TRFQ_COUNTERPARTY + { + P_SYSID = 83442, + PARTYNAME = "中国银行股份有限公司", + PARTYNAME_SHORT = "中国银行", + }); + updateList.Add(new TRFQ_COUNTERPARTY + { + P_SYSID = 83442, + PARTYNAME = "中国银行股份有限公司", + PARTYNAME_SHORT = "中国银行", + }); + updateList.Add(new TRFQ_COUNTERPARTY + { + P_SYSID = 83442, + PARTYNAME = "中国银行股份有限公司", + PARTYNAME_SHORT = "中国银行", + }); + updateList.Add(new TRFQ_COUNTERPARTY + { + P_SYSID = 83442, + PARTYNAME = "中国银行股份有限公司", + PARTYNAME_SHORT = "中国银行", + }); + updateList.Add(new TRFQ_COUNTERPARTY + { + P_SYSID = 83442, + PARTYNAME = "中国银行股份有限公司", + PARTYNAME_SHORT = "中国银行", + }); + updateList.Add(new TRFQ_COUNTERPARTY + { + P_SYSID = 83442, + PARTYNAME = "中国银行股份有限公司", + PARTYNAME_SHORT = "中国银行", + }); + updateList.Add(new TRFQ_COUNTERPARTY + { + P_SYSID = 83442, + PARTYNAME = "中国银行股份有限公司", + PARTYNAME_SHORT = "中国银行", + }); + updateList.Add(new TRFQ_COUNTERPARTY + { + P_SYSID = 83442, + PARTYNAME = "中国银行股份有限公司", + PARTYNAME_SHORT = "中国银行", + }); + updateList.Add(new TRFQ_COUNTERPARTY + { + P_SYSID = 83442, + PARTYNAME = "中国银行股份有限公司", + PARTYNAME_SHORT = "中国银行", + }); + //修改 + db.Updateable(updateList).UpdateColumns(["PARTYNAME", "PARTYNAME_SHORT"]).ExecuteCommand(); + } + } +} diff --git a/Src/Asp.NetCore2/4TDSQLForOracleODBCTest/TRFQ_COUNTERPARTY.cs b/Src/Asp.NetCore2/4TDSQLForOracleODBCTest/TRFQ_COUNTERPARTY.cs new file mode 100644 index 0000000000000000000000000000000000000000..a7cef1ffc9875dc1f06474af32041c455a786dba --- /dev/null +++ b/Src/Asp.NetCore2/4TDSQLForOracleODBCTest/TRFQ_COUNTERPARTY.cs @@ -0,0 +1,315 @@ +using System; +using System.Collections.Generic; +using SqlSugar; + +namespace xTPLM.RFQ.Model.XRFQ_APP +{ + /// + ///交易对手表 + /// + [SugarTable("TRFQ_COUNTERPARTY")] + public partial class TRFQ_COUNTERPARTY + { + public TRFQ_COUNTERPARTY() + { + + + } + /// + /// Desc:主键 + /// Default: + /// Nullable:False + /// + [SugarColumn(IsNullable = false, IsPrimaryKey = true, OracleSequenceName = "TRFQ_COUNTERPARTY$SEQ", IsIdentity = true)] + public int P_SYSID { get; set; } + + /// + /// Desc:名称 + /// Default: + /// Nullable:False + /// + [SugarColumn(IsNullable = false, Length = 1000)] + public string PARTYNAME { get; set; } + + /// + /// Desc:简称 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 200)] + public string PARTYNAME_SHORT { get; set; } + + /// + /// Desc:启用状态:0=停用;1=启用 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public int? PARTYSTATUS { get; set; } + + /// + /// 是否启用 + /// + [SugarColumn(IsIgnore = true)] + public bool IsOpen + { + get + { + return this.PARTYSTATUS == 1; + } + set + { + this.PARTYSTATUS = value ? 1 : 0; + } + } + + /// + /// Desc:银行间会员代码 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 50)] + public string CNBD_MEMBERID { get; set; } + + /// + /// Desc:外汇21位机构代码 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 50)] + public string CNBD_ORGCODE { get; set; } + + /// + /// Desc:所在地域 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 50)] + public string BELONGTOAREA { get; set; } + + /// + /// Desc:上交所固收平台交易商代码 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 32)] + public string SHG_FIX_CUSTCODE { get; set; } + + /// + /// Desc:新增类型:0:手动,1:自动 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 10)] + public string PARTYSOURCE { get; set; } + + /// + /// Desc:统一社会信用代码 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 100)] + public string CREDITCODE { get; set; } + + /// + /// Desc:法人代表 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 200)] + public string LEGALPERSON { get; set; } + + /// + /// Desc:营业执照有效日期 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 10)] + public string EXPDATE { get; set; } + + /// + /// Desc:备注 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 500)] + public string REMARK { get; set; } + + /// + /// Desc:外汇做市商类型:0 非做市商,1 做市商,2 尝试做市商-综合做市,3 尝试做市商-专项做市 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 10)] + public string MARKETMAKER_TYPE { get; set; } + + /// + /// Desc:最后更新人 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 32)] + public string UPDATED_BY { get; set; } + + /// + /// Desc:最后更新时间 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public DateTime? UPDATED_TIME { get; set; } + + /// + /// Desc:别名 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 1000)] + public string ALIAS { get; set; } + + /// + /// Desc:外部ID + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public int? P_EXTID { get; set; } + + /// + /// Desc:导入时间 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public DateTime? IMPORTTIME { get; set; } + + /// + /// Desc:所属机构 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public int? PARENTORGANPARTYID { get; set; } + + /// + /// Desc:客户信评等级 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 50)] + public string CREDITLEVEL { get; set; } + + /// + /// 净资产 + /// + [SugarColumn(IsNullable = true)] + public decimal? PARTY_NET_ASSETS { get; set; } + + /// + /// 交易对手名称_拼音首拼 + /// + [SugarColumn(IsNullable = true, Length = 512)] + public string PARTYNAME_PINYIN { get; set; } + + /// + /// 交易对手简称_拼音首拼 + /// + [SugarColumn(IsNullable = true, Length = 512)] + public string PARTYNAME_SHORT_PINYIN { get; set; } + + /// + /// 是否法人:1,法人;0,非法人 + /// + [SugarColumn(IsNullable = true, Length = 1)] + public string ISLEGALPERSON { get; set; } + + /// + /// 募集方式 + /// + [SugarColumn(IsNullable = true, Length = 128)] + public string RAISEWAY { get; set; } + + #region 数据库忽略字段 + + /// + /// 对手类型描述 + /// + [SugarColumn(IsIgnore = true)] + public string PARTY_TYPE_DESC + { + get + { + if (ISLEGALPERSON == "0") + { + return "非法人户"; + } + else if (ISLEGALPERSON == "1") + { + return "法人户"; + } + + return string.Empty; + } + } + + /// + /// 所属机构名称 + /// + [SugarColumn(IsIgnore = true)] + public string PARENTORGANPARTY { get; set; } + + /// + /// 更新人名称 + /// + [SugarColumn(IsIgnore = true)] + public string UPDATED_BY_NAME { get; set; } + + /// + /// 是否满足入库标准 + /// + [SugarColumn(IsIgnore = true)] + public int? IS_CHECK_SUCCESS { get; set; } + + /// + /// 是否符合入库标准(尽调表需求) + /// + [SugarColumn(IsIgnore = true)] + public bool? IS_STANDARD + { + get + { + if (this.IS_CHECK_SUCCESS.HasValue) + { + return this.IS_CHECK_SUCCESS == 1; + } + else + { + return null; + } + } + } + + /// + /// 尽调表到期日 + /// + [SugarColumn(IsIgnore = true)] + public DateTime? END_DATE { get; set; } + + /// + /// 尽调表是否到期 + /// + [SugarColumn(IsIgnore = true)] + public bool IsEnd + { + get + { + if (END_DATE.HasValue) + { + return END_DATE.Value.Date < DateTime.Now.Date; + } + return false; + } + } + #endregion + } +} diff --git a/Src/Asp.NetCore2/4TDSQLForOracleODBCTest/TRFQ_QUOTATION.cs b/Src/Asp.NetCore2/4TDSQLForOracleODBCTest/TRFQ_QUOTATION.cs new file mode 100644 index 0000000000000000000000000000000000000000..9f7c80f0c0a1d0da6ad9c7a330caf571f7712060 --- /dev/null +++ b/Src/Asp.NetCore2/4TDSQLForOracleODBCTest/TRFQ_QUOTATION.cs @@ -0,0 +1,654 @@ +using Newtonsoft.Json; +using SqlSugar; + +namespace xTPLM.RFQ.Model.XRFQ_APP +{ + /// + ///询价记录表 + /// + [SugarTable("TRFQ_QUOTATION")] + public partial class TRFQ_QUOTATION + { + /// + /// 询价序列名称 + /// + public const string SequenceName = "TRFQ_QUOTATION$SEQ"; + public TRFQ_QUOTATION() + { + + + } + /// + /// Desc:主键序号自增序列 + /// Default: + /// Nullable:False + /// + [SugarColumn(IsNullable = false, IsPrimaryKey = true, OracleSequenceName = SequenceName, IsIdentity = true)] + public int Q_SYSID { get; set; } + + /// + /// Desc:QQ号(由于对接QTrade,所以当CONTACTNUMBER_TYPE=2时,此字段存储QT号) + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 50)] + public string QQ_NUMBER { get; set; } + + /// + /// Desc:本方交易员 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 100)] + public string SELF_TRADER { get; set; } + + /// + /// Desc:执行市场 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 50)] + public string EXE_MARKET { get; set; } + + /// + /// Desc:金融工具Code + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 100)] + public string I_CODE { get; set; } + + /// + /// Desc:金融工具A_TYPE + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 100)] + public string A_TYPE { get; set; } + + /// + /// Desc:金融工具M_TYPE + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 100)] + public string M_TYPE { get; set; } + + /// + /// Desc:面额(万) + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public decimal? ORDER_MONEY { get; set; } + + /// + /// 实际面额 + /// 基于剩余本金计算 + /// + [SugarColumn(IsNullable = true)] + public decimal? ACTUAL_AMOUNT { get; set; } + + /// + /// Desc:到期收益率 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public decimal? BND_YTM { get; set; } + + /// + /// Desc:行权收益率 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public decimal? BND_YTM_OE { get; set; } + + /// + /// Desc:净价 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public decimal? BND_NETPRICE { get; set; } + + /// + /// Desc:全价 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public decimal? BND_PRICE { get; set; } + + /// + /// Desc:交易方向 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 50)] + public int? TRADER_TYPE { get; set; } + + /// + /// Desc:交易日期 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public DateTime? ORDER_DATE { get; set; } + + /// + /// Desc:结算日期 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public DateTime? SETDATE { get; set; } + + /// + /// Desc:清算速度 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, ColumnDataType = "INT")] + public int? SET_DAYS { get; set; } + + /// + /// Desc:交易对手 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public int? PARTY_ID { get; set; } + + /// + /// Desc:实际交易对手 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public int? PARTYID_ACTUAL { get; set; } + + /// + /// Desc:对方交易员 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public int? TRADER_CP { get; set; } + + /// + /// Desc:报价发起方 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 1)] + public int? QUOTE_SPONSOR { get; set; } + + /// + /// Desc:预期报价方式 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, ColumnName = "DEAL_TYPE", ColumnDataType = "INT")] + public int? DEAL_TYPE { get; set; } + + /// + /// Desc:中介机构 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 50)] + public string INTERMEDIATION { get; set; } + + /// + /// Desc:上交所固收平台约定号 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 20)] + public string SHG_AGREENUM { get; set; } + + /// + /// Desc:上交所固收平台对手方交易员代码 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 50)] + public string SHG_TRADER_CP { get; set; } + + /// + /// Desc:上交所固收平台对手方席位号 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 50)] + public string SHG_SEATNO_CP { get; set; } + + /// + /// Desc:导入时间 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public DateTime? IMPORT_TIME { get; set; } + + /// + /// Desc:交易备注 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 1000)] + public string REMARK { get; set; } + + /// + /// Desc:交易是否删除:0未删除 1删除 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public int IS_DELETE { get; set; } = 0; + + /// + /// Desc:询价状态 + /// Default: + /// Nullable:True + /// + [SugarColumn(ColumnName = "Q_STATUS", ColumnDataType = "INT")] + public int? Q_STATUS { get; set; } + + + /// + /// Desc:反向报价(和本表的主键关联) + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public int? SYSID_INVERSE { get; set; } + + /// + /// Desc:交易系统交易 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public int? SYSID_EXT { get; set; } + + /// + /// Desc:公开级别,0:个人,1:小组,2:公共 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public int? Q_PUBLICLEVEL { get; set; } + + /// + /// Desc:报价来源, + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, ColumnDataType = "INT")] + public int? Q_BID_SOURCE { get; set; } + + /// + /// Desc:外部交易标识 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 128)] + public string EXT_TRADE_ID { get; set; } + + /// + /// Desc:最后一次修改时间 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public DateTime? UPDATE_TIME { get; set; } + + /// + /// Desc:最后一次修改人 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 32)] + public string UPDATE_BY { get; set; } + + /// + /// Desc:外部联系账号类型:1-QQ号,2-QT号 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public int? CONTACTNUMBER_TYPE { get; set; } + + /// + /// Desc:价格类型: 1-到期收益率 2-行权收益率 3-净价 4-全价 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, ColumnDataType = "INT")] + public int? PRICE_TYPE { get; set; } + + /// + /// Desc:下达状态 0:未下达,5:下达中,10:下达成功,-1:下达失败 + /// Default: + /// Nullable:False + /// + [SugarColumn(IsNullable = false, ColumnName = "RELEASE_STATUS")] + public int RELEASE_STATUS { get; set; } + + /// + /// Desc:下达信息 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 1024)] + public string RELEASE_MESSAGE { get; set; } + + /// + /// Desc:下达时间 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public DateTime? RELEASE_TIME { get; set; } + + /// + /// Desc:内政账户 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 64)] + public string SECU_ACCID { get; set; } + + /// + /// Desc:本方操作员 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 64)] + public int? SELF_OPERATOR { get; set; } + + /// + /// Desc:交易执行员 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 64)] + public string EXECUTOR { get; set; } + + /// + /// Desc:xIR交易组合ID + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 64)] + public string GRPID { get; set; } + + /// + /// Desc:xIR交易组合名称 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 512)] + public string GRPNAME { get; set; } + + /// + /// Desc:xIR交易子组合ID + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 64)] + public string CHILDGROUPID { get; set; } + + /// + /// Desc:xIR交易子组合名称 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 512)] + public string CHILDGROUPNAME { get; set; } + + /// + /// Desc:自定义组合类型 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 64)] + public string GRPTYPE_CUSTOM { get; set; } + + /// + /// Desc:自定义子组合类型 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 64)] + public string CHILDGRPTYPE_CUSTOM { get; set; } + + /// + /// Desc:临时交易对手 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 128)] + public string PARTYNAMETEMPORITY { get; set; } + + /// + /// Desc:创建时间 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public DateTime? CREATE_TIME { get; set; } + + /// + /// Desc:中介费用 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true)] + public decimal? INTERMEDIARY_FEE { get; set; } + + /// + /// Desc:报价执行员 + /// Default: + /// Nullable:True + /// + [SugarColumn(IsNullable = true, Length = 128)] + public string EXECUTETRADER { get; set; } + + /// + /// XIR交易系统状态 + /// + [SugarColumn(IsNullable = true)] + public int? TRADESYSTEM_STATUS { get; set; } + + /// + /// 对手方交易商代码 + /// + [SugarColumn(IsNullable = true, Length = 256)] + public string DEALER_CODE { get; set; } + + /// + /// 对手方交易主体代码 + /// + [SugarColumn(IsNullable = true, Length = 256)] + public string TRADEBODY_CODE { get; set; } + + /// + /// 拆分前询价ID(用于记录该询价是否是拆分询价,并记录拆分前的询价ID) + /// + [SugarColumn(IsNullable = true)] + public int? ORI_QID { get; set; } + + /// + /// 首期结算状态 #该字段目前没有落地,当作数据库忽略字段使用 + /// + [SugarColumn(IsNullable = true)] + public int? FST_STATE { get; set; } + + /// + /// 到期结算状态 #该字段目前没有落地,当作数据库忽略字段使用 + /// + [SugarColumn(IsNullable = true)] + public int? END_STATE { get; set; } + + /// + /// 应计利息 + /// + [SugarColumn(IsNullable = true)] + public decimal? AIAMOUNT { get; set; } + + /// + /// 结算金额 + /// + [SugarColumn(IsNullable = true)] + public decimal? ORDAMOUNT { get; set; } + + /// + /// 外部成交编号 + /// + [SugarColumn(IsNullable = true)] + public string EXTORDID { get; set; } + + /// + /// 原始文本 + /// + [SugarColumn(IsNullable = true, Length = 2000)] + public string ORIGNAL_TEXT { get; set; } + + /// + /// 实际交易对手信息 + /// + [SugarColumn(IsNullable = true, Length = 200)] + public string ACTUALPARTY_LINKMAN { get; set; } + + /// + /// 本方交易商 + /// + [SugarColumn(IsNullable = true, Length = 512)] + public string SELF_DEALER { get; set; } + + /// + /// 本方交易主体 + /// + [SugarColumn(IsNullable = true, Length = 512)] + public string SELF_INVESTOR { get; set; } + + /// + /// 对手方主体类型 + /// + [SugarColumn(IsNullable = true, Length = 512)] + public string CP_INVESTOR_TYPE { get; set; } + + /// + /// 投资经理 + /// + [SugarColumn(IsNullable = true, Length = 1024)] + public int? INVESTMENT_MANAGER { get; set; } + + /// + /// 询价备注 + /// + [SugarColumn(IsNullable = true, Length = 4000)] + public string QUOTA_REMARK { get; set; } + + /// + /// 是否内部询价(交易) 1:是 + /// + [SugarColumn(IsNullable = true)] + public int? IS_INTERNAL { get; set; } + + /// + /// 对手方内部证券账户 + /// + [SugarColumn(IsNullable = true, Length = 256)] + public string SECU_INT_CP { get; set; } + + /// + /// 内部对手交易员 + /// + [SugarColumn(IsNullable = true, Length = 512)] + public string SECU_TRADER_CP { get; set; } + + /// + /// 数据来源 系统简称(接口导入时,存储导入的系统标识) + /// + public string SOURCE_TYPE { get; set; } + + /// + /// 预计收益率 + /// + public decimal? EXPECTED_YIELD { get; set; } + + /// + /// 单张应计利息 + /// + public decimal? UNIT_AIAMOUNT { get; set; } + + /// + /// 报价途径 + /// + [SugarColumn(IsNullable = true, Length = 64)] + public string QUOTECHANNEL { get; set; } + + /// + /// 当前审批角色 + /// + public string APPROVALUSER { get; set; } + + #region 资管字段 + /// + /// 产品ID(内资代码) + /// + [SugarColumn(IsNullable = true, Length = 128)] + public string CASH_ACCID { get; set; } + + + #region 数据库忽略字段 + + /// + /// 产品名称 + /// + [SugarColumn(IsIgnore = true)] + public string PRODUCT_NAME { get; set; } + + #endregion + + #endregion + + /// + /// 将询价价格设置为有效价格 + /// + public void QuotaPriceAuth() + { + //收益率不能小于0,不能大于10000 + if (this.BND_YTM >= 10000 || this.BND_YTM < 0) + { + this.BND_YTM = 0; + } + + //收益率不能小于0,不能大于10000 + if (this.BND_YTM_OE >= 10000 || this.BND_YTM_OE < 0) + { + this.BND_YTM_OE = 0; + } + + //全价不能小于0 + if (this.BND_PRICE < 0) + { + this.BND_PRICE = 0; + } + + //净价不能小于0 + if (this.BND_NETPRICE < 0) + { + this.BND_NETPRICE = 0; + } + } + + + + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.OceanBaseForOracle/OceanBase/DbBind/OceanBaseForOracleDbBind.cs b/Src/Asp.NetCore2/SqlSugar.OceanBaseForOracle/OceanBase/DbBind/OceanBaseForOracleDbBind.cs index c886c81f274a9de2c77b09350f16e0bb7dad27e0..d72715e5aca95ca772fd75fa3da16659aa6f29c4 100644 --- a/Src/Asp.NetCore2/SqlSugar.OceanBaseForOracle/OceanBase/DbBind/OceanBaseForOracleDbBind.cs +++ b/Src/Asp.NetCore2/SqlSugar.OceanBaseForOracle/OceanBase/DbBind/OceanBaseForOracleDbBind.cs @@ -31,6 +31,10 @@ namespace SqlSugar.OceanBaseForOracle { dbTypeName = dbTypeName.ToLower(); var propertyTypes = MappingTypes.Where(it => it.Value.ToString().ToLower() == dbTypeName || it.Key.ToLower() == dbTypeName); + if (dbTypeName == "text") + { + return "other"; + } if (dbTypeName == "int32") { return "int"; diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/DataTableExtensions/TDSQLForOracleDataAdapter.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/DataTableExtensions/TDSQLForOracleDataAdapter.cs new file mode 100644 index 0000000000000000000000000000000000000000..9ffbe5d2ab5bcdef194f85adc0583f6fe8e3d564 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/DataTableExtensions/TDSQLForOracleDataAdapter.cs @@ -0,0 +1,111 @@ +using System.Data; +using System.Data.Odbc; +namespace SqlSugar.TDSQLForOracleODBC +{ + /// + /// 数据填充器 + /// + public class TDSQLForOracleDataAdapter : IDataAdapter + { + private OdbcCommand command; + private string sql; + private OdbcConnection _sqlConnection; + + /// + /// SqlDataAdapter + /// + /// + public TDSQLForOracleDataAdapter(OdbcCommand command) + { + this.command = command; + } + + public TDSQLForOracleDataAdapter() + { + + } + + /// + /// SqlDataAdapter + /// + /// + /// + public TDSQLForOracleDataAdapter(string sql, OdbcConnection _sqlConnection) + { + this.sql = sql; + this._sqlConnection = _sqlConnection; + } + + /// + /// SelectCommand + /// + public OdbcCommand SelectCommand + { + get + { + if (this.command == null) + { + var conn = (OdbcConnection)this._sqlConnection; + this.command = conn.CreateCommand(); + this.command.CommandText = sql; + } + return this.command; + } + set + { + this.command = value; + } + } + + /// + /// Fill + /// + /// + public void Fill(DataTable dt) + { + if (dt == null) + { + dt = new DataTable(); + } + var columns = dt.Columns; + var rows = dt.Rows; + using (var dr = command.ExecuteReader()) + { + for (int i = 0; i < dr.FieldCount; i++) + { + string name = dr.GetName(i).Trim(); + if (!columns.Contains(name)) + columns.Add(new DataColumn(name, dr.GetFieldType(i))); + else + { + columns.Add(new DataColumn(name + i, dr.GetFieldType(i))); + } + } + + while (dr.Read()) + { + DataRow daRow = dt.NewRow(); + for (int i = 0; i < columns.Count; i++) + { + daRow[columns[i].ColumnName] = dr.GetValue(i); + } + dt.Rows.Add(daRow); + } + } + dt.AcceptChanges(); + } + + /// + /// Fill + /// + /// + public void Fill(DataSet ds) + { + using (var cmd = new OdbcDataAdapter(this.SelectCommand)) + { + cmd.Fill(ds); + } + } + } + +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/SqlSugar.TDSQLForOracleODBC.csproj b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/SqlSugar.TDSQLForOracleODBC.csproj new file mode 100644 index 0000000000000000000000000000000000000000..550f4a6ed2f4157c34ab02800458891b0a471795 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/SqlSugar.TDSQLForOracleODBC.csproj @@ -0,0 +1,26 @@ + + + + netstandard2.1 + 5.33.4.216 + sun_kai_xuan,guoshun.du + http://191.168.1.27:8080/back-end/xquant.sqlsugar + + + xQuant.SqlSugar.TDSQLForOracleODBC + 果糖大数据科技(南通)有限公司 + 果糖大数据科技(南通)有限公司 + 果糖大数据科技(南通)有限公司 + True + True + + + + + + + + + + + diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/CodeFirst/TDSQLForOracleODBCCodeFirst.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/CodeFirst/TDSQLForOracleODBCCodeFirst.cs new file mode 100644 index 0000000000000000000000000000000000000000..2c2d3c61a1d954e83a8d85b2288b8ab39d1bb381 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/CodeFirst/TDSQLForOracleODBCCodeFirst.cs @@ -0,0 +1,47 @@ +using System; + +namespace SqlSugar.TDSQLForOracleODBC +{ + public class TDSQLForOracleODBCCodeFirst : CodeFirstProvider + { + public TDSQLForOracleODBCCodeFirst() + { + if (DefultLength == 0) + DefultLength = 40; + } + protected override int DefultLength { get; set; } + + protected override void GetDbType(EntityColumnInfo item, Type propertyType, DbColumnInfo result) + { + if (!string.IsNullOrEmpty(item.DataType)) + { + result.DataType = item.DataType; + } + else if (propertyType.IsEnum()) + { + result.DataType = this.Context.Ado.DbBind.GetDbTypeName(item.Length > 9 ? UtilConstants.LongType.Name : UtilConstants.IntType.Name); + } + else + { + if (propertyType.Name.Equals("Guid", StringComparison.CurrentCultureIgnoreCase)) + { + result.DataType = this.Context.Ado.DbBind.GetDbTypeName(UtilConstants.StringType.Name); + if (result.Length <= 1) + { + result.Length = 36; + } + } + else + { + result.DataType = this.Context.Ado.DbBind.GetDbTypeName(propertyType.Name); + } + } + } + + protected override void KeyAction(EntityColumnInfo item, DbColumnInfo dbColumn, out bool pkDiff, out bool idEntityDiff) + { + pkDiff = item.IsPrimarykey != dbColumn.IsPrimarykey; + idEntityDiff = false; + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/DbBind/TDSQLForOracleODBCDbBind.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/DbBind/TDSQLForOracleODBCDbBind.cs new file mode 100644 index 0000000000000000000000000000000000000000..fc348aa30211374edc3c67f09cafac4f61d5b863 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/DbBind/TDSQLForOracleODBCDbBind.cs @@ -0,0 +1,197 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace SqlSugar.TDSQLForOracleODBC +{ + public class TDSQLForOracleODBCDbBind : DbBindProvider + { + public override string GetDbTypeName(string csharpTypeName) + { + csharpTypeName = GetValidCsharpTypeName(csharpTypeName); + if (csharpTypeName == UtilConstants.ByteArrayType.Name) + return "bytea"; + if (csharpTypeName.ToLower() == "int32") + csharpTypeName = "int"; + if (csharpTypeName.ToLower() == "int16") + csharpTypeName = "short"; + if (csharpTypeName.ToLower() == "int64") + csharpTypeName = "long"; + if (csharpTypeName.ToLower().IsIn("boolean", "bool")) + csharpTypeName = "bool"; + if (csharpTypeName == "DateTimeOffset") + return "timestamptz"; + var mappings = this.MappingTypes.Where(it => it.Value.ToString().Equals(csharpTypeName, StringComparison.CurrentCultureIgnoreCase)).ToList(); + if (mappings != null && mappings.Count > 0) + return mappings.First().Key; + else + return "varchar"; + } + + private string GetValidCsharpTypeName(string csharpTypeName) + { + if (csharpTypeName?.StartsWith("ora") == true && this.Context.CurrentConnectionConfig?.MoreSettings?.DatabaseModel == DbType.Vastbase) + { + csharpTypeName = csharpTypeName.Replace("ora", ""); + } + else if (csharpTypeName?.StartsWith("mssql_") == true && this.Context.CurrentConnectionConfig?.MoreSettings?.DatabaseModel == DbType.Vastbase) + { + csharpTypeName = csharpTypeName.Replace("mssql_", ""); + } + else if (csharpTypeName?.StartsWith("sys.") == true) + { + csharpTypeName = csharpTypeName.Replace("sys.", ""); + } + return csharpTypeName; + } + + public override string GetPropertyTypeName(string dbTypeName) + { + dbTypeName = dbTypeName.ToLower(); + dbTypeName = GetValidCsharpTypeName(dbTypeName); + var propertyTypes = MappingTypes.Where(it => it.Value.ToString().ToLower() == dbTypeName || it.Key.ToLower() == dbTypeName); + if (dbTypeName == "text") + { + return "other"; + } + if (propertyTypes == null || dbTypeName == "unknown") + { + return "other"; + } + else if (dbTypeName == "xml" || dbTypeName == "string" || dbTypeName == "jsonb" || dbTypeName == "json") + { + return "string"; + } + else if (dbTypeName == "bpchar")//数据库char datatype 查询出来的时候是 bpchar + { + return "char"; + } + if (dbTypeName == "byte[]") + { + return "byte[]"; + } + else if (propertyTypes == null || propertyTypes.Count() == 0) + { + if (dbTypeName.StartsWith("_")) + { + var dbTypeName2 = dbTypeName.TrimStart('_'); + return MappingTypes.Where(it => it.Value.ToString().ToLower() == dbTypeName2 || it.Key.ToLower() == dbTypeName2).Select(it => it.Value + "[]").First(); + } + else if (dbTypeName.EndsWith("geometry") || dbTypeName.EndsWith("geography")) + { + return CSharpDataType.@string.ToString(); + } + Check.ThrowNotSupportedException(string.Format(" \"{0}\" Type NotSupported, DbBindProvider.GetPropertyTypeName error.", dbTypeName)); + return null; + } + else if (propertyTypes.First().Value == CSharpDataType.byteArray) + { + return "byte[]"; + } + else + { + return propertyTypes.First().Value.ToString(); + } + } + public override List> MappingTypes + { + get + { + var extService = this.Context.CurrentConnectionConfig.ConfigureExternalServices; + if (extService != null && extService.AppendDataReaderTypeMappings.HasValue()) + { + return extService.AppendDataReaderTypeMappings.Union(MappingTypesConst).ToList(); + } + else + { + return MappingTypesConst; + } + } + } + public static List> MappingTypesConst = new List>(){ + + new KeyValuePair("int2",CSharpDataType.@short), + //new KeyValuePair("int1",CSharpDataType.@byte), + new KeyValuePair("smallint",CSharpDataType.@short), + new KeyValuePair("smallint",CSharpDataType.@byte), + new KeyValuePair("int4",CSharpDataType.@int), + new KeyValuePair("serial",CSharpDataType.@int), + new KeyValuePair("integer",CSharpDataType.@int), + new KeyValuePair("int8",CSharpDataType.@long), + new KeyValuePair("long",CSharpDataType.@long), + new KeyValuePair("bigint",CSharpDataType.@long), + new KeyValuePair("float4",CSharpDataType.@float), + new KeyValuePair("float4",CSharpDataType.Single), + new KeyValuePair("real",CSharpDataType.@float), + new KeyValuePair("float8",CSharpDataType.@double), + new KeyValuePair("double precision",CSharpDataType.@int), + new KeyValuePair("numeric",CSharpDataType.@decimal), + new KeyValuePair("decimal",CSharpDataType.@decimal), + new KeyValuePair("path",CSharpDataType.@decimal), + new KeyValuePair("point",CSharpDataType.@decimal), + new KeyValuePair("polygon",CSharpDataType.@decimal), + + new KeyValuePair("boolean",CSharpDataType.@bool), + new KeyValuePair("bool",CSharpDataType.@bool), + new KeyValuePair("box",CSharpDataType.@bool), + new KeyValuePair("bytea",CSharpDataType.byteArray), + + new KeyValuePair("varchar",CSharpDataType.@string), + new KeyValuePair("clob",CSharpDataType.@string), + new KeyValuePair("nvarchar2",CSharpDataType.@string), + new KeyValuePair("varchar2",CSharpDataType.@string), + new KeyValuePair("character varying",CSharpDataType.@string), + new KeyValuePair("geometry",CSharpDataType.@string), + new KeyValuePair("name",CSharpDataType.@string), + new KeyValuePair("text",CSharpDataType.@string), + new KeyValuePair("char",CSharpDataType.@string), + new KeyValuePair("character",CSharpDataType.@string), + new KeyValuePair("cidr",CSharpDataType.@string), + new KeyValuePair("circle",CSharpDataType.@string), + new KeyValuePair("tsquery",CSharpDataType.@string), + new KeyValuePair("tsvector",CSharpDataType.@string), + new KeyValuePair("txid_snapshot",CSharpDataType.@string), + new KeyValuePair("uuid",CSharpDataType.Guid), + new KeyValuePair("xml",CSharpDataType.@string), + new KeyValuePair("json",CSharpDataType.@string), + + new KeyValuePair("interval",CSharpDataType.@decimal), + new KeyValuePair("lseg",CSharpDataType.@decimal), + new KeyValuePair("macaddr",CSharpDataType.@decimal), + new KeyValuePair("money",CSharpDataType.@decimal), + new KeyValuePair("timestamp",CSharpDataType.DateTime), + new KeyValuePair("timestamp with time zone",CSharpDataType.DateTime), + new KeyValuePair("timestamptz",CSharpDataType.DateTime), + new KeyValuePair("timestamp without time zone",CSharpDataType.DateTime), + new KeyValuePair("date",CSharpDataType.DateTime), + new KeyValuePair("time",CSharpDataType.DateTime), + new KeyValuePair("time with time zone",CSharpDataType.DateTime), + new KeyValuePair("timetz",CSharpDataType.DateTime), + new KeyValuePair("time without time zone",CSharpDataType.DateTime), + + new KeyValuePair("bit",CSharpDataType.byteArray), + new KeyValuePair("bit varying",CSharpDataType.byteArray), + new KeyValuePair("varbit",CSharpDataType.@byte), + new KeyValuePair("time",CSharpDataType.TimeSpan), + new KeyValuePair("public.geometry",CSharpDataType.@object), + new KeyValuePair("public.geography",CSharpDataType.@object), + new KeyValuePair("inet",CSharpDataType.@object), + + new KeyValuePair("number",CSharpDataType.@int), + new KeyValuePair("number",CSharpDataType.@float), + new KeyValuePair("number",CSharpDataType.@short), + new KeyValuePair("number",CSharpDataType.@byte), + new KeyValuePair("number",CSharpDataType.@double), + new KeyValuePair("number",CSharpDataType.@long), + new KeyValuePair("number",CSharpDataType.@bool), + new KeyValuePair("number",CSharpDataType.@decimal), + }; + public override List StringThrow + { + get + { + return new List() { "int32", "datetime", "decimal", "double", "byte" }; + } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/DbFirst/TDSQLForOracleODBCDbFirst.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/DbFirst/TDSQLForOracleODBCDbFirst.cs new file mode 100644 index 0000000000000000000000000000000000000000..2ab4fc5ebd509ba85937f8033eca7aefcdb4f884 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/DbFirst/TDSQLForOracleODBCDbFirst.cs @@ -0,0 +1,6 @@ +namespace SqlSugar.TDSQLForOracleODBC +{ + public class TDSQLForOracleODBCDbFirst : DbFirstProvider + { + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/DbMaintenance/TDSQLForOracleODBCDbMaintenance.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/DbMaintenance/TDSQLForOracleODBCDbMaintenance.cs new file mode 100644 index 0000000000000000000000000000000000000000..c45d7b7751571e22e33e4bda3a518b256b0862e3 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/DbMaintenance/TDSQLForOracleODBCDbMaintenance.cs @@ -0,0 +1,659 @@ +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.Linq; +using System.Text.RegularExpressions; + +namespace SqlSugar.TDSQLForOracleODBC +{ + public class TDSQLForOracleODBCDbMaintenance : DbMaintenanceProvider + { + #region DML + protected override string GetDataBaseSql + { + get + { + return "SELECT datname FROM pg_database"; + } + } + protected override string GetColumnInfosByTableNameSql + { + get + { + string schema = GetSchema(); + string sql = @"select cast (pclass.oid as int4) as TableId,cast(ptables.tablename as varchar) as TableName, + pcolumn.column_name as DbColumnName,pcolumn.udt_name as DataType, + CASE WHEN pcolumn.numeric_scale >0 THEN pcolumn.numeric_precision ELSE pcolumn.character_maximum_length END as Length, + pcolumn.column_default as DefaultValue, + pcolumn.numeric_scale as DecimalDigits, + pcolumn.numeric_scale as Scale, + col_description(pclass.oid, pcolumn.ordinal_position) as ColumnDescription, + case when pkey.colname = pcolumn.column_name + then true else false end as IsPrimaryKey, + CASE + WHEN (current_setting('server_version_num')::INT >= 100000 AND pcolumn.is_identity = 'YES') THEN true + WHEN pcolumn.column_default LIKE 'nextval%' THEN true + ELSE false + END AS IsIdentity, + case when pcolumn.is_nullable = 'YES' + then true else false end as IsNullable + from (select * from pg_tables where upper(tablename) = upper('{0}') and schemaname='" + schema + @"') ptables inner join pg_class pclass + on ptables.tablename = pclass.relname inner join (SELECT * + FROM information_schema.columns where table_schema='" + schema + @"' + ) pcolumn on pcolumn.table_name = ptables.tablename and upper(pcolumn.table_name) = upper('{0}') + left join ( + select pg_class.relname,pg_attribute.attname as colname from + pg_constraint inner join pg_class + on pg_constraint.conrelid = pg_class.oid + inner join pg_attribute on pg_attribute.attrelid = pg_class.oid + and pg_attribute.attnum = pg_constraint.conkey[1] + inner join pg_type on pg_type.oid = pg_attribute.atttypid + where pg_constraint.contype='p' + ) pkey on pcolumn.table_name = pkey.relname + order by table_catalog, table_schema, ordinal_position"; + return sql; + } + } + + protected override string GetTableInfoListSql + { + get + { + var schema = GetSchema(); + return @"select cast(relname as varchar) as Name, + cast(obj_description(c.oid,'pg_class') as varchar) as Description from pg_class c + inner join + pg_namespace n on n.oid = c.relnamespace and nspname='" + schema + @"' + inner join + pg_tables z on z.tablename=c.relname + where relkind in('p', 'r') and relname not like 'pg\_%' and relname not like 'sql\_%' and schemaname='" + schema + "' order by relname"; + } + } + protected override string GetViewInfoListSql + { + get + { + return @"select table_name as name from information_schema.views where table_schema ='" + GetSchema() + "' "; + } + } + #endregion + + #region DDL + protected override string CreateDataBaseSql + { + get + { + return "CREATE DATABASE {0}"; + } + } + protected override string AddPrimaryKeySql + { + get + { + return "ALTER TABLE {0} ADD PRIMARY KEY({2}) /*{1}*/"; + } + } + protected override string AddColumnToTableSql + { + get + { + return "ALTER TABLE {0} ADD COLUMN {1} {2}{3} {4} {5} {6}"; + } + } + protected override string AlterColumnToTableSql + { + get + { + return "alter table {0} ALTER COLUMN {1} {2}{3} {4} {5} {6}"; + } + } + protected override string BackupDataBaseSql + { + get + { + return "mysqldump.exe {0} -uroot -p > {1} "; + } + } + protected override string CreateTableSql + { + get + { + return "CREATE TABLE {0}(\r\n{1} $PrimaryKey)"; + } + } + protected override string CreateTableColumn + { + get + { + return "{0} {1}{2} {3} {4} {5}"; + } + } + protected override string TruncateTableSql + { + get + { + return "TRUNCATE TABLE {0}"; + } + } + protected override string BackupTableSql + { + get + { + return "create table {0} as (select * from {1} limit {2} offset 0)"; + } + } + protected override string DropTableSql + { + get + { + return "DROP TABLE {0}"; + } + } + protected override string DropColumnToTableSql + { + get + { + return "ALTER TABLE {0} DROP COLUMN {1}"; + } + } + protected override string DropConstraintSql + { + get + { + return "ALTER TABLE {0} DROP CONSTRAINT {1}"; + } + } + protected override string RenameColumnSql + { + get + { + return "ALTER TABLE {0} RENAME {1} TO {2}"; + } + } + protected override string AddColumnRemarkSql => "comment on column {1}.{0} is '{2}'"; + + protected override string DeleteColumnRemarkSql => "comment on column {1}.{0} is ''"; + + protected override string IsAnyColumnRemarkSql { get { throw new NotSupportedException(); } } + + protected override string AddTableRemarkSql => "comment on table {0} is '{1}'"; + + protected override string DeleteTableRemarkSql => "comment on table {0} is ''"; + + protected override string IsAnyTableRemarkSql { get { throw new NotSupportedException(); } } + + protected override string RenameTableSql => "alter table {0} rename to {1}"; + + protected override string CreateIndexSql + { + get + { + return "CREATE {3} INDEX Index_{0}_{2} ON {0} ({1})"; + } + } + protected override string AddDefaultValueSql + { + get + { + return "ALTER TABLE {0} ALTER COLUMN {1} SET DEFAULT {2}"; + } + } + protected override string IsAnyIndexSql + { + get + { + return " SELECT count(1) WHERE upper('{0}') IN ( SELECT upper(indexname) FROM pg_indexes )"; + } + } + protected override string IsAnyProcedureSql => throw new NotImplementedException(); + #endregion + + #region Check + protected override string CheckSystemTablePermissionsSql + { + get + { + return "select 1 from information_schema.columns limit 1 offset 0"; + } + } + #endregion + + #region Scattered + protected override string CreateTableNull + { + get + { + return "DEFAULT NULL"; + } + } + protected override string CreateTableNotNull + { + get + { + return "NOT NULL"; + } + } + protected override string CreateTablePirmaryKey + { + get + { + return "PRIMARY KEY"; + } + } + protected override string CreateTableIdentity + { + get + { + return "serial"; + } + } + #endregion + + #region Methods + public override bool IsAnyTable(string tableName, bool isCache = true) + { + if (isCache == false) + { + var sql = $" SELECT 1 FROM pg_catalog.pg_tables \r\n WHERE schemaname = '" + GetSchema() + "' \r\n AND Lower(tablename) = '" + tableName.ToLower() + "' "; + return this.Context.Ado.GetInt(sql) > 0; + } + else + { + return base.IsAnyTable(tableName, isCache); + } + } + public override List GetDbTypes() + { + var result = this.Context.Ado.SqlQuery(@"SELECT DISTINCT data_type +FROM information_schema.columns"); + result.Add("varchar"); + result.Add("timestamp"); + result.Add("uuid"); + result.Add("int2"); + result.Add("int4"); + result.Add("int8"); + result.Add("time"); + result.Add("date"); + result.Add("float8"); + result.Add("float4"); + result.Add("json"); + result.Add("jsonp"); + return result.Distinct().ToList(); + } + public override List GetTriggerNames(string tableName) + { + return this.Context.Ado.SqlQuery(@"SELECT tgname +FROM pg_trigger +WHERE tgrelid = '" + tableName + "'::regclass"); + } + public override List GetFuncList() + { + return this.Context.Ado.SqlQuery(" SELECT routine_name\r\nFROM information_schema.routines\r\nWHERE lower( routine_schema ) = '" + GetSchema().ToLower() + "' AND routine_type = 'FUNCTION' "); + } + public override List GetIndexList(string tableName) + { + var sql = $"SELECT indexname, indexdef FROM pg_indexes WHERE upper(tablename) = upper('{tableName}') AND upper(schemaname) = upper('{GetSchema()}')"; + return this.Context.Ado.SqlQuery(sql); + } + public override List GetProcList(string dbName) + { + var sql = $"SELECT proname FROM pg_proc p JOIN pg_namespace n ON p.pronamespace = n.oid WHERE n.nspname = '{dbName}'"; + return this.Context.Ado.SqlQuery(sql); + } + public override bool AddDefaultValue(string tableName, string columnName, string defaultValue) + { + if (defaultValue?.StartsWith("'") == true && defaultValue?.EndsWith("'") == true && defaultValue?.Contains("(") == false + && !defaultValue.EqualCase("'current_timestamp'") && !defaultValue.EqualCase("'current_date'")) + { + string sql = string.Format(AddDefaultValueSql, this.SqlBuilder.GetTranslationColumnName(tableName), this.SqlBuilder.GetTranslationColumnName(columnName), defaultValue); + return this.Context.Ado.ExecuteCommand(sql) > 0; + } + else if (defaultValue.EqualCase("current_timestamp") || defaultValue.EqualCase("current_date")) + { + string sql = string.Format(AddDefaultValueSql, this.SqlBuilder.GetTranslationColumnName(tableName), this.SqlBuilder.GetTranslationColumnName(columnName), defaultValue); + return this.Context.Ado.ExecuteCommand(sql) > 0; + } + else if (defaultValue?.Contains("(") == false + && !defaultValue.EqualCase("'current_timestamp'") && !defaultValue.EqualCase("'current_date'")) + { + string sql = string.Format(AddDefaultValueSql, this.SqlBuilder.GetTranslationColumnName(tableName), this.SqlBuilder.GetTranslationColumnName(columnName), "'" + defaultValue + "'"); + return this.Context.Ado.ExecuteCommand(sql) > 0; + } + else if (defaultValue?.ToLower()?.Contains("cast(") == true && defaultValue?.StartsWith("'") == true && defaultValue?.EndsWith("'") == true) + { + string sql = string.Format(AddDefaultValueSql, this.SqlBuilder.GetTranslationColumnName(tableName), this.SqlBuilder.GetTranslationColumnName(columnName), defaultValue.Replace("''", "'").TrimEnd('\'').TrimStart('\'')); + return this.Context.Ado.ExecuteCommand(sql) > 0; + } + else if (defaultValue?.ToLower()?.Contains("now()") == true) + { + string sql = string.Format(AddDefaultValueSql, this.SqlBuilder.GetTranslationColumnName(tableName), this.SqlBuilder.GetTranslationColumnName(columnName), defaultValue.TrimEnd('\'').TrimStart('\'')); + return this.Context.Ado.ExecuteCommand(sql) > 0; + } + else + { + return base.AddDefaultValue(this.SqlBuilder.GetTranslationTableName(tableName), this.SqlBuilder.GetTranslationTableName(columnName), defaultValue); + } + } + + public override bool RenameTable(string oldTableName, string newTableName) + { + return base.RenameTable(this.SqlBuilder.GetTranslationTableName(oldTableName), this.SqlBuilder.GetTranslationTableName(newTableName)); + } + + public override bool AddColumnRemark(string columnName, string tableName, string description) + { + tableName = this.SqlBuilder.GetTranslationTableName(tableName); + string sql = string.Format(this.AddColumnRemarkSql, this.SqlBuilder.GetTranslationColumnName(columnName.ToLower(isAutoToLowerCodeFirst)), tableName, description); + this.Context.Ado.ExecuteCommand(sql); + return true; + } + public override bool AddTableRemark(string tableName, string description) + { + tableName = this.SqlBuilder.GetTranslationTableName(tableName); + return base.AddTableRemark(tableName, description); + } + public override bool UpdateColumn(string tableName, DbColumnInfo columnInfo) + { + ConvertCreateColumnInfo(columnInfo); + tableName = this.SqlBuilder.GetTranslationTableName(tableName); + var columnName = this.SqlBuilder.GetTranslationColumnName(columnInfo.DbColumnName); + string sql = GetUpdateColumnSql(tableName, columnInfo); + this.Context.Ado.ExecuteCommand(sql); + var isnull = columnInfo.IsNullable ? " DROP NOT NULL " : " SET NOT NULL "; + this.Context.Ado.ExecuteCommand(string.Format("alter table {0} alter {1} {2}", tableName, columnName, isnull)); + return true; + } + + protected override string GetUpdateColumnSql(string tableName, DbColumnInfo columnInfo) + { + string columnName = this.SqlBuilder.GetTranslationColumnName(columnInfo.DbColumnName); + tableName = this.SqlBuilder.GetTranslationTableName(tableName); + string dataSize = GetSize(columnInfo); + string dataType = columnInfo.DataType; + if (!string.IsNullOrEmpty(dataType)) + { + dataType = " type " + dataType; + } + string nullType = ""; + string primaryKey = null; + string identity = null; + string result = string.Format(this.AlterColumnToTableSql, tableName, columnName, dataType, dataSize, nullType, primaryKey, identity); + return result; + } + + /// + ///by current connection string + /// + /// + /// + public override bool CreateDatabase(string databaseName, string databaseDirectory = null) + { + if (databaseDirectory != null) + { + if (!FileHelper.IsExistDirectory(databaseDirectory)) + { + FileHelper.CreateDirectory(databaseDirectory); + } + } + var oldDatabaseName = this.Context.Ado.Connection.Database; + var connection = this.Context.CurrentConnectionConfig.ConnectionString; + if (Regex.Matches(connection, oldDatabaseName).Count > 1) + { + var builder = new Npgsql.NpgsqlConnectionStringBuilder(connection); + builder.Database = "postgres"; + connection = builder.ConnectionString; + } + else + { + connection = connection.Replace(oldDatabaseName, "postgres"); + } + var newDb = new SqlSugarClient(new ConnectionConfig() + { + DbType = this.Context.CurrentConnectionConfig.DbType, + IsAutoCloseConnection = true, + ConnectionString = connection + }); + if (!GetDataBaseList(newDb).Any(it => it.Equals(databaseName, StringComparison.CurrentCultureIgnoreCase))) + { + var isVast = this.Context?.CurrentConnectionConfig?.MoreSettings?.DatabaseModel == DbType.Vastbase; + var dbcompatibility = ""; + if (isVast) + { + dbcompatibility = " dbcompatibility = 'PG'"; + } + newDb.Ado.ExecuteCommand(string.Format(CreateDataBaseSql, this.SqlBuilder.SqlTranslationLeft + databaseName + this.SqlBuilder.SqlTranslationRight, databaseDirectory) + dbcompatibility); + } + return true; + } + public override bool AddRemark(EntityInfo entity) + { + var db = this.Context; + var columns = entity.Columns.Where(it => it.IsIgnore == false).ToList(); + + foreach (var item in columns) + { + if (item.ColumnDescription != null) + { + db.DbMaintenance.AddColumnRemark(item.DbColumnName, item.DbTableName, item.ColumnDescription); + + } + } + //table remak + if (entity.TableDescription != null) + { + db.DbMaintenance.AddTableRemark(entity.DbTableName, entity.TableDescription); + } + return true; + } + public override bool CreateTable(string tableName, List columns, bool isCreatePrimaryKey = true) + { + if (columns.HasValue()) + { + foreach (var item in columns) + { + ConvertCreateColumnInfo(item); + if (item.DbColumnName.Equals("GUID", StringComparison.CurrentCultureIgnoreCase) && item.Length == 0) + { + if (item.DataType?.ToLower() != "uuid") + { + item.Length = 10; + } + } + } + } + string sql = GetCreateTableSql(tableName, columns); + string primaryKeyInfo = null; + if (columns.Any(it => it.IsPrimarykey) && isCreatePrimaryKey) + { + primaryKeyInfo = string.Format(", Primary key({0})", string.Join(",", columns.Where(it => it.IsPrimarykey).Select(it => this.SqlBuilder.GetTranslationColumnName(it.DbColumnName.ToLower(isAutoToLowerCodeFirst))))); + + } + sql = sql.Replace("$PrimaryKey", primaryKeyInfo); + this.Context.Ado.ExecuteCommand(sql); + return true; + } + protected override bool IsAnyDefaultValue(string tableName, string columnName, List columns) + { + var defaultValue = columns.Where(it => it.DbColumnName.Equals(columnName, StringComparison.CurrentCultureIgnoreCase)).First().DefaultValue; + if (defaultValue?.StartsWith("NULL::") == true) + { + return false; + } + return defaultValue.HasValue(); + } + protected override string GetCreateTableSql(string tableName, List columns) + { + List columnArray = new List(); + Check.Exception(columns.IsNullOrEmpty(), "No columns found "); + foreach (var item in columns) + { + string columnName = item.DbColumnName; + string dataType = item.DataType; + if (dataType == "varchar" && item.Length == 0) + { + item.Length = 1; + } + //if (dataType == "uuid") + //{ + // item.Length = 50; + // dataType = "varchar"; + //} + string dataSize = item.Length > 0 ? string.Format("({0})", item.Length) : null; + if (item.DecimalDigits > 0 && item.Length > 0 && dataType == "numeric") + { + dataSize = $"({item.Length},{item.DecimalDigits})"; + } + string nullType = item.IsNullable ? this.CreateTableNull : CreateTableNotNull; + string primaryKey = null; + string addItem = string.Format(this.CreateTableColumn, this.SqlBuilder.GetTranslationColumnName(columnName.ToLower(isAutoToLowerCodeFirst)), dataType, dataSize, nullType, primaryKey, ""); + if (item.IsIdentity) + { + if (dataType?.ToLower() == "int") + { + dataSize = "int4"; + } + else if (dataType?.ToLower() == "long") + { + dataSize = "int8"; + } + string length = dataType.Substring(dataType.Length - 1); + string identityDataType = "serial" + length; + addItem = addItem.Replace(dataType, identityDataType); + } + columnArray.Add(addItem); + } + string tableString = string.Format(this.CreateTableSql, this.SqlBuilder.GetTranslationTableName(tableName.ToLower(isAutoToLowerCodeFirst)), string.Join(",\r\n", columnArray)); + return tableString; + } + public override bool IsAnyConstraint(string constraintName) + { + throw new NotSupportedException("PgSql IsAnyConstraint NotSupportedException"); + } + public override bool BackupDataBase(string databaseName, string fullFileName) + { + Check.ThrowNotSupportedException("PgSql BackupDataBase NotSupported"); + return false; + } + + public override List GetColumnInfosByTableName(string tableName, bool isCache = true) + { + var result = base.GetColumnInfosByTableName(tableName.TrimEnd('"').TrimStart('"').ToLower(), isCache); + if (result == null || result.Count() == 0) + { + result = base.GetColumnInfosByTableName(tableName, isCache); + } + try + { + string sql = $@"select + kcu.column_name as key_column + from information_schema.table_constraints tco + join information_schema.key_column_usage kcu + on kcu.constraint_name = tco.constraint_name + and kcu.constraint_schema = tco.constraint_schema + and kcu.constraint_name = tco.constraint_name + where tco.constraint_type = 'PRIMARY KEY' + and kcu.table_schema='{GetSchema()}' and + upper(kcu.table_name)=upper('{tableName.TrimEnd('"').TrimStart('"')}')"; + List pkList = new List(); + if (isCache) + { + pkList = GetListOrCache("GetColumnInfosByTableName_N_Pk" + tableName, sql); + } + else + { + pkList = this.Context.Ado.SqlQuery(sql); + } + if (pkList.Count > 1) + { + foreach (var item in result) + { + if (pkList.Select(it => it.ToUpper()).Contains(item.DbColumnName.ToUpper())) + { + item.IsPrimarykey = true; + } + } + } + } + catch + { + + } + return result; + } + #endregion + + #region Helper + private bool isAutoToLowerCodeFirst + { + get + { + if (this.Context.CurrentConnectionConfig.MoreSettings == null) return true; + else if ( + this.Context.CurrentConnectionConfig.MoreSettings.PgSqlIsAutoToLower == false && + this.Context.CurrentConnectionConfig.MoreSettings?.PgSqlIsAutoToLowerCodeFirst == false) + { + return false; + } + else + { + return true; + } + } + } + private string GetSchema() + { + var schema = "public"; + var pgSqlIsAutoToLowerSchema = this.Context?.CurrentConnectionConfig?.MoreSettings?.PgSqlIsAutoToLowerSchema == false; + if (pgSqlIsAutoToLowerSchema) + { + if (System.Text.RegularExpressions.Regex.IsMatch(this.Context.CurrentConnectionConfig.ConnectionString, "searchpath=", RegexOptions.IgnoreCase)) + { + var regValue = System.Text.RegularExpressions.Regex.Match(this.Context.CurrentConnectionConfig.ConnectionString, @"searchpath\=(\w+)").Groups[1].Value; + if (regValue.HasValue()) + { + schema = regValue; + } + } + else if (System.Text.RegularExpressions.Regex.IsMatch(this.Context.CurrentConnectionConfig.ConnectionString, "search path=", RegexOptions.IgnoreCase)) + { + var regValue = System.Text.RegularExpressions.Regex.Match(this.Context.CurrentConnectionConfig.ConnectionString.ToLower(), @"search path\=(\w+)").Groups[1].Value; + if (regValue.HasValue()) + { + schema = regValue; + } + } + } + else + { + if (System.Text.RegularExpressions.Regex.IsMatch(this.Context.CurrentConnectionConfig.ConnectionString.ToLower(), "searchpath=")) + { + var regValue = System.Text.RegularExpressions.Regex.Match(this.Context.CurrentConnectionConfig.ConnectionString.ToLower(), @"searchpath\=(\w+)").Groups[1].Value; + if (regValue.HasValue()) + { + schema = regValue; + } + } + else if (System.Text.RegularExpressions.Regex.IsMatch(this.Context.CurrentConnectionConfig.ConnectionString.ToLower(), "search path=")) + { + var regValue = System.Text.RegularExpressions.Regex.Match(this.Context.CurrentConnectionConfig.ConnectionString.ToLower(), @"search path\=(\w+)").Groups[1].Value; + if (regValue.HasValue()) + { + schema = regValue; + } + } + } + return schema; + } + private static void ConvertCreateColumnInfo(DbColumnInfo x) + { + string[] array = new string[] { "uuid", "int4", "text", "int2", "int8", "date", "bit", "text", "timestamp" }; + + if (array.Contains(x.DataType?.ToLower())) + { + x.Length = 0; + x.DecimalDigits = 0; + } + } + #endregion + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/Deleteable/TDSQLForOracleODBCDeleteable.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/Deleteable/TDSQLForOracleODBCDeleteable.cs new file mode 100644 index 0000000000000000000000000000000000000000..7643a046b32831838aba08d22eed78cdcdc2c12f --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/Deleteable/TDSQLForOracleODBCDeleteable.cs @@ -0,0 +1,14 @@ +using SqlSugar; +using System.Collections.Generic; +using System.Linq; + +namespace SqlSugar.TDSQLForOracleODBC +{ + public class TDSQLForOracleODBCDeleteable : DeleteableProvider where T : class, new() + { + protected override List GetIdentityKeys() + { + return this.EntityInfo.Columns.Where(it => it.OracleSequenceName.HasValue()).Select(it => it.DbColumnName).ToList(); + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/Insertable/TDSQLForOracleODBCInsertable.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/Insertable/TDSQLForOracleODBCInsertable.cs new file mode 100644 index 0000000000000000000000000000000000000000..bdfb2c8ba548fd44427e24054a3fc9b4be29e408 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/Insertable/TDSQLForOracleODBCInsertable.cs @@ -0,0 +1,242 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SqlSugar.TDSQLForOracleODBC +{ + public class TDSQLForOracleODBCInsertable : InsertableProvider where T : class, new() + { + protected override List GetIdentityKeys() + { + return this.EntityInfo.Columns.Where(it => it.OracleSequenceName.HasValue()).Select(it => it.DbColumnName).ToList(); + } + protected string GetSeqName() + { + return this.EntityInfo.Columns.Where(it => it.OracleSequenceName.HasValue()).Select(it => it.OracleSequenceName).First(); + } + protected List GetSeqNames() + { + return this.EntityInfo.Columns.Where(it => it.OracleSequenceName.HasValue()).Select(it => it.OracleSequenceName).ToList(); + } + public override int ExecuteReturnIdentity() + { + bool oldIsAuto = AutoBegin(); + + InsertBuilder.IsReturnIdentity = true; + PreToSql(); + string sql = InsertBuilder.ToSqlString(); + if (isIdEntityEnable()) + { + if (sql?.StartsWith("INSERT ALL") == true) + { + return this.UseParameter().ExecuteCommand(); + } + else + { + // sql = sql + " RETURNING ID INTO :newId01 "; + } + //InsertBuilder.Parameters.Add(new SugarParameter(":newId01", 0,true)); + } + RestoreMapping(); + string identityColumn = GetIdentityColumn(); + sql = sql.Replace("$PrimaryKey", this.SqlBuilder.GetTranslationColumnName(identityColumn)); + var isDisableMasterSlaveSeparation = this.Context.Ado.IsDisableMasterSlaveSeparation; + this.Context.Ado.IsDisableMasterSlaveSeparation = true; + var result = Ado.GetScalar(sql, InsertBuilder.Parameters == null ? null : InsertBuilder.Parameters.ToArray()).ObjToInt(); + this.Context.Ado.IsDisableMasterSlaveSeparation = isDisableMasterSlaveSeparation; + After(sql, result); + AutoEnd(oldIsAuto); + if (isIdEntityEnable()) + { + var name = this.EntityInfo.Columns.First(it => it.IsIdentity).DbColumnName; + return this.Context.Ado.GetInt(" SELECT MAX(" + this.InsertBuilder.Builder.GetTranslationColumnName(name) + ") FROM " + this.InsertBuilder.GetTableNameString); + } + return result; + } + private bool isIdEntityEnable() + { + return this.Context.CurrentConnectionConfig?.MoreSettings?.EnableOracleIdentity == true; + } + + public override long ExecuteReturnBigIdentity() + { + bool oldIsAuto = AutoBegin(); + + InsertBuilder.IsReturnIdentity = true; + PreToSql(); + string sql = InsertBuilder.ToSqlString(); + if (isIdEntityEnable()) + { + if (sql?.StartsWith("INSERT ALL") == true) + { + return this.UseParameter().ExecuteCommand(); + } + else + { + //sql = sql + " RETURNING ID INTO :newId01 "; + } + //InsertBuilder.Parameters.Add(new SugarParameter(":newId01", Convert.ToInt64(0), true)); + } + RestoreMapping(); + string identityColumn = GetIdentityColumn(); + sql = sql.Replace("$PrimaryKey", this.SqlBuilder.GetTranslationColumnName(identityColumn)); + var isDisableMasterSlaveSeparation = this.Context.Ado.IsDisableMasterSlaveSeparation; + this.Context.Ado.IsDisableMasterSlaveSeparation = true; + var result = Ado.GetScalar(sql, InsertBuilder.Parameters == null ? null : InsertBuilder.Parameters.ToArray()).ObjToLong(); + this.Context.Ado.IsDisableMasterSlaveSeparation = isDisableMasterSlaveSeparation; + After(sql, result); + AutoEnd(oldIsAuto); + if (isIdEntityEnable()) + { + var name = this.EntityInfo.Columns.First(it => it.IsIdentity).DbColumnName; + return this.Context.Ado.GetInt(" SELECT MAX(" + this.InsertBuilder.Builder.GetTranslationColumnName(name) + ") FROM " + this.InsertBuilder.GetTableNameString); + } + return result; + } + + public async override Task ExecuteReturnIdentityAsync() + { + bool oldIsAuto = AutoBegin(); + + InsertBuilder.IsReturnIdentity = true; + PreToSql(); + string sql = InsertBuilder.ToSqlString(); + if (isIdEntityEnable()) + { + if (sql?.StartsWith("INSERT ALL") == true) + { + return await this.UseParameter().ExecuteCommandAsync(); + } + else + { + //sql = sql + " RETURNING ID INTO :newId01 "; + } + //InsertBuilder.Parameters.Add(new SugarParameter(":newId01", 0, true)); + } + RestoreMapping(); + string identityColumn = GetIdentityColumn(); + sql = sql.Replace("$PrimaryKey", this.SqlBuilder.GetTranslationColumnName(identityColumn)); + var isDisableMasterSlaveSeparation = this.Context.Ado.IsDisableMasterSlaveSeparation; + this.Context.Ado.IsDisableMasterSlaveSeparation = true; + var result = (await Ado.GetScalarAsync(sql, InsertBuilder.Parameters == null ? null : InsertBuilder.Parameters.ToArray())).ObjToInt(); + this.Context.Ado.IsDisableMasterSlaveSeparation = isDisableMasterSlaveSeparation; + After(sql, result); + AutoEnd(oldIsAuto); + if (isIdEntityEnable()) + { + var name = this.EntityInfo.Columns.First(it => it.IsIdentity).DbColumnName; + return await this.Context.Ado.GetIntAsync(" SELECT MAX(" + this.InsertBuilder.Builder.GetTranslationColumnName(name) + ") FROM " + this.InsertBuilder.GetTableNameString); + } + return result; + } + + public async override Task ExecuteReturnBigIdentityAsync() + { + bool oldIsAuto = AutoBegin(); + + InsertBuilder.IsReturnIdentity = true; + PreToSql(); + string sql = InsertBuilder.ToSqlString(); + if (isIdEntityEnable()) + { + if (sql?.StartsWith("INSERT ALL") == true) + { + return await this.UseParameter().ExecuteCommandAsync(); + } + else + { + //sql = sql + " RETURNING ID INTO :newId01 "; + } + //InsertBuilder.Parameters.Add(new SugarParameter(":newId01", Convert.ToInt64(0), true)); + } + RestoreMapping(); + string identityColumn = GetIdentityColumn(); + sql = sql.Replace("$PrimaryKey", this.SqlBuilder.GetTranslationColumnName(identityColumn)); + var isDisableMasterSlaveSeparation = this.Context.Ado.IsDisableMasterSlaveSeparation; + this.Context.Ado.IsDisableMasterSlaveSeparation = true; + var result = (await Ado.GetScalarAsync(sql, InsertBuilder.Parameters == null ? null : InsertBuilder.Parameters.ToArray())).ObjToLong(); + this.Context.Ado.IsDisableMasterSlaveSeparation = isDisableMasterSlaveSeparation; + After(sql, result); + AutoEnd(oldIsAuto); + if (isIdEntityEnable()) + { + var name = this.EntityInfo.Columns.First(it => it.IsIdentity).DbColumnName; + return this.Context.Ado.GetInt(" SELECT MAX(" + this.InsertBuilder.Builder.GetTranslationColumnName(name) + ") FROM " + this.InsertBuilder.GetTableNameString); + } + return result; + } + + private void AutoEnd(bool oldIsAuto) + { + if (oldIsAuto) + { + this.Context.Context.CurrentConnectionConfig.IsAutoCloseConnection = oldIsAuto; + if (this.Ado.Transaction == null) + this.Context.Ado.Close(); + } + } + + private bool AutoBegin() + { + var oldIsAuto = this.Context.Context.CurrentConnectionConfig.IsAutoCloseConnection; + if (this.Context.Context.CurrentConnectionConfig.IsAutoCloseConnection) + { + this.Context.Context.CurrentConnectionConfig.IsAutoCloseConnection = false; + } + + return oldIsAuto; + } + //private object GetSeqValue(string seqName) + //{ + // return Ado.GetScalar(" SELECT " + seqName + ".currval FROM DUAL"); + //} + protected override void PreToSql() + { + var identities = GetSeqNames(); + var insertCount = InsertObjs.Count(); + InsertBuilder.OracleSeqInfoList = new Dictionary(); + if ((identities.HasValue() && insertCount > 1) || InsertBuilder.IsBlukCopy) + { + Check.Exception(identities.Count != identities.Distinct().Count(), "The field sequence needs to be unique"); + foreach (var seqName in identities) + { + int seqBeginValue = 0; + seqBeginValue = this.Ado.GetInt("select " + seqName + ".Nextval from dual"); + //Console.WriteLine(seqBeginValue); + var nextLength = insertCount - 1; + if (nextLength > 0) + { + StringBuilder sb = new StringBuilder(); + sb.AppendLine(" select " + seqName + ".nextval,t.* from ("); + for (int i = 0; i < nextLength; i++) + { + sb.AppendLine(" select 1 from dual"); + if (i < (nextLength - 1)) + { + sb.AppendLine("union all"); + } + } + sb.AppendLine(" )t"); + this.Ado.SqlQuery(sb.ToString()); + } + InsertBuilder.OracleSeqInfoList.Add(seqName, seqBeginValue); + } + } + base.PreToSql(); + } + + + private string GetIdentityColumn() + { + var identityColumn = GetIdentityKeys().FirstOrDefault(); + if (identityColumn == null) + { + var columns = this.Context.DbMaintenance.GetColumnInfosByTableName(InsertBuilder.GetTableNameString); + identityColumn = columns.First(it => it.IsIdentity || it.IsPrimarykey).DbColumnName; + } + return identityColumn; + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/Queryable/TDSQLForOracleODBCQueryable.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/Queryable/TDSQLForOracleODBCQueryable.cs new file mode 100644 index 0000000000000000000000000000000000000000..21545e0288271a4a489a6e7b323d3a5d0367c586 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/Queryable/TDSQLForOracleODBCQueryable.cs @@ -0,0 +1,62 @@ +using SqlSugar; +using System.Collections.Generic; +using System.Linq; + +namespace SqlSugar.TDSQLForOracleODBC +{ + public class TDSQLForOracleODBCQueryable : QueryableProvider + { + public override ISugarQueryable With(string withString) + { + return this; + } + protected override List GetIdentityKeys() + { + return this.EntityInfo.Columns.Where(it => it.OracleSequenceName.HasValue()).Select(it => it.DbColumnName).ToList(); + } + } + public class TDSQLForOracleODBCQueryable : QueryableProvider + { + + } + public class TDSQLForOracleODBCQueryable : QueryableProvider + { + + } + public class TDSQLForOracleODBCQueryable : QueryableProvider + { + + } + public class TDSQLForOracleODBCQueryable : QueryableProvider + { + + } + public class TDSQLForOracleODBCQueryable : QueryableProvider + { + + } + public class TDSQLForOracleODBCQueryable : QueryableProvider + { + + } + public class TDSQLForOracleODBCQueryable : QueryableProvider + { + + } + public class TDSQLForOracleODBCQueryable : QueryableProvider + { + + } + public class TDSQLForOracleODBCQueryable : QueryableProvider + { + + } + public class TDSQLForOracleODBCQueryable : QueryableProvider + { + + } + public class TDSQLForOracleODBCQueryable : QueryableProvider + { + + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCBlukCopy.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCBlukCopy.cs new file mode 100644 index 0000000000000000000000000000000000000000..7fe776440ef60351b1bf9550ebb7014c04a5371a --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCBlukCopy.cs @@ -0,0 +1,153 @@ +using Microsoft.Data.SqlClient; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Threading.Tasks; + +namespace SqlSugar.TDSQLForOracleODBC +{ + public class TDSQLForOracleODBCBlukCopy + { + internal List> DbColumnInfoList { get; set; } + internal SqlSugarProvider Context { get; set; } + internal ISqlBuilder Builder { get; set; } + internal InsertBuilder InsertBuilder { get; set; } + internal object[] Inserts { get; set; } + + public int ExecuteBulkCopy() + { + if (DbColumnInfoList == null || DbColumnInfoList.Count == 0) return 0; + + if (Inserts.First().GetType() == typeof(DataTable)) + { + return WriteToServer(); + } + DataTable dt = GetCopyData(); + SqlBulkCopy bulkCopy = GetBulkCopyInstance(); + bulkCopy.DestinationTableName = InsertBuilder.GetTableNameString; + try + { + bulkCopy.WriteToServer(dt); + } + catch (Exception ex) + { + CloseDb(); + throw ex; + } + CloseDb(); + return DbColumnInfoList.Count; + } + + public async Task ExecuteBulkCopyAsync() + { + if (DbColumnInfoList == null || DbColumnInfoList.Count == 0) return 0; + + if (Inserts.First().GetType() == typeof(DataTable)) + { + return WriteToServer(); + } + DataTable dt = GetCopyData(); + SqlBulkCopy bulkCopy = GetBulkCopyInstance(); + bulkCopy.DestinationTableName = InsertBuilder.GetTableNameString; + try + { + await bulkCopy.WriteToServerAsync(dt); + } + catch (Exception ex) + { + CloseDb(); + throw ex; + } + CloseDb(); + return DbColumnInfoList.Count; + } + + private int WriteToServer() + { + var dt = this.Inserts.First() as DataTable; + if (dt == null) + return 0; + Check.Exception(dt.TableName == "Table", "dt.TableName can't be null "); + dt = GetCopyWriteDataTable(dt); + SqlBulkCopy copy = GetBulkCopyInstance(); + copy.DestinationTableName = this.Builder.GetTranslationColumnName(dt.TableName); + copy.WriteToServer(dt); + CloseDb(); + return dt.Rows.Count; + } + private DataTable GetCopyWriteDataTable(DataTable dt) + { + var result = this.Context.Ado.GetDataTable("select top 0 * from " + this.Builder.GetTranslationColumnName(dt.TableName)); + foreach (DataRow item in dt.Rows) + { + DataRow dr = result.NewRow(); + foreach (DataColumn column in result.Columns) + { + + if (dt.Columns.Cast().Select(it => it.ColumnName.ToLower()).Contains(column.ColumnName.ToLower())) + { + dr[column.ColumnName] = item[column.ColumnName]; + if (dr[column.ColumnName] == null) + { + dr[column.ColumnName] = DBNull.Value; + } + } + } + result.Rows.Add(dr); + } + result.TableName = dt.TableName; + return result; + } + private SqlBulkCopy GetBulkCopyInstance() + { + SqlBulkCopy copy; + if (this.Context.Ado.Transaction == null) + { + copy = new SqlBulkCopy((SqlConnection)this.Context.Ado.Connection); + } + else + { + copy = new SqlBulkCopy((SqlConnection)this.Context.Ado.Connection, SqlBulkCopyOptions.CheckConstraints, (SqlTransaction)this.Context.Ado.Transaction); + } + if (this.Context.Ado.Connection.State == ConnectionState.Closed) + { + this.Context.Ado.Connection.Open(); + } + copy.BulkCopyTimeout = this.Context.Ado.CommandTimeOut; + return copy; + } + private DataTable GetCopyData() + { + var dt = this.Context.Ado.GetDataTable("select top 0 * from " + InsertBuilder.GetTableNameString); + foreach (var rowInfos in DbColumnInfoList) + { + var dr = dt.NewRow(); + foreach (var value in rowInfos) + { + if (value.Value != null && UtilMethods.GetUnderType(value.Value.GetType()) == UtilConstants.DateType) + { + if (value.Value != null && value.Value.ToString() == DateTime.MinValue.ToString()) + { + value.Value = Convert.ToDateTime("1753/01/01"); + } + } + if (value.Value == null) + { + value.Value = DBNull.Value; + } + dr[value.DbColumnName] = value.Value; + } + dt.Rows.Add(dr); + } + return dt; + } + private void CloseDb() + { + if (this.Context.CurrentConnectionConfig.IsAutoCloseConnection && this.Context.Ado.Transaction == null) + { + this.Context.Ado.Connection.Close(); + } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCBuilder.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCBuilder.cs new file mode 100644 index 0000000000000000000000000000000000000000..6bd3c6453e23d2e2e542eab2b98555c7a897eb4f --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCBuilder.cs @@ -0,0 +1,74 @@ +namespace SqlSugar.TDSQLForOracleODBC +{ + public class TDSQLForOracleODBCBuilder : SqlBuilderProvider + { + public override string SqlParameterKeyWord + { + get + { + return ":"; + } + } + public override string SqlDateNow + { + get + { + return "sysdate"; + } + } + public override string FullSqlDateNow + { + get + { + return "select systimestamp from dual"; + } + } + public override string SqlTranslationLeft { get { return "\""; } } + public override string SqlTranslationRight { get { return "\""; } } + public override string GetTranslationTableName(string name) + { + var result = base.GetTranslationTableName(name); + if (result.Contains("(") && result.Contains(")")) + return result; + else + return result.ToUpper(IsUppper); + } + public override string GetTranslationColumnName(string entityName, string propertyName) + { + var result = base.GetTranslationColumnName(entityName, propertyName); + return result.ToUpper(IsUppper); + } + public override string GetTranslationColumnName(string propertyName) + { + var result = base.GetTranslationColumnName(propertyName); + return result.ToUpper(IsUppper); + } + public override string RemoveParentheses(string sql) + { + if (sql.StartsWith("(") && sql.EndsWith(")")) + { + sql = sql.Substring(1, sql.Length - 2); + } + + return sql; + } + #region Helper + public bool IsUppper + { + get + { + if (this.Context.CurrentConnectionConfig.MoreSettings == null) + { + return true; + } + else + { + return this.Context.CurrentConnectionConfig.MoreSettings.IsAutoToUpper == true; + } + } + } + #endregion + + } + +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCDeleteBuilder.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCDeleteBuilder.cs new file mode 100644 index 0000000000000000000000000000000000000000..69e6710ef9168fc98d7ab20adf3ab37a281599a2 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCDeleteBuilder.cs @@ -0,0 +1,7 @@ +namespace SqlSugar.TDSQLForOracleODBC +{ + public class TDSQLForOracleODBCDeleteBuilder : DeleteBuilder + { + + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCExpressionContext.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCExpressionContext.cs new file mode 100644 index 0000000000000000000000000000000000000000..cad7418e2a6dabc87ecdbcf20d635c5d7e848159 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCExpressionContext.cs @@ -0,0 +1,467 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +namespace SqlSugar.TDSQLForOracleODBC +{ + public partial class TDSQLForOracleODBCExpressionContext : ExpressionContext, ILambdaExpressions + { + public SqlSugarProvider Context { get; set; } + public TDSQLForOracleODBCExpressionContext() + { + base.DbMehtods = new OceanBaseForOracleMethod(); + base.Case = new ExpressionContextCase(); + } + public override string SqlParameterKeyWord + { + get + { + return ":"; + } + } + public override string SqlTranslationLeft { get { return "\""; } } + public override string SqlTranslationRight { get { return "\""; } } + public override string GetTranslationTableName(string entityName, bool isMapping = true) + { + return base.GetTranslationTableName(entityName, isMapping).ToUpper(IsUppper); + } + public override string GetTranslationColumnName(string columnName) + { + if (columnName == "systimestamp") + { + return columnName; + } + if (columnName.Contains(":")) + return base.GetTranslationColumnName(columnName); + else if (columnName.Contains("\".\"")) + { + return columnName; + } + else + return base.GetTranslationColumnName(columnName).ToUpper(IsUppper); + } + public override string GetDbColumnName(string entityName, string propertyName) + { + return base.GetDbColumnName(entityName, propertyName).ToUpper(IsUppper); + } + public override bool IsTranslationText(string name) + { + if (!string.IsNullOrEmpty(name) && name.ToLower() == "sysdate") + { + return true; + } + var result = name.IsContainsIn(SqlTranslationLeft, SqlTranslationRight, UtilConstants.Space, ExpressionConst.LeftParenthesis, ExpressionConst.RightParenthesis); + return result; + } + public bool IsUppper + { + get + { + if (this.SugarContext?.Context?.Context?.CurrentConnectionConfig?.MoreSettings == null) + { + return true; + } + else + { + return this.SugarContext?.Context?.Context?.CurrentConnectionConfig?.MoreSettings.IsAutoToUpper == true; + } + } + } + + public override string GetLimit() + { + int num = 1; + if (this.Case?.Num > 1) + { + num = this.Case.Num; + } + return (this.Case?.HasWhere == true ? "AND" : "WHERE") + " ROWNUM=" + num; + } + } + public partial class OceanBaseForOracleMethod : DefaultDbMethod, IDbMethods + { + public override string UNIX_TIMESTAMP(MethodCallExpressionModel model) + { + var parameterNameA = model.Args[0].MemberName; + return $" (CAST({parameterNameA} AS DATE) - DATE '1970-01-01') * 86400 "; + } + public override string IsNullOrEmpty(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format("( {0} IS NULL )", parameter.MemberName); + } + public override string WeekOfYear(MethodCallExpressionModel mode) + { + var parameterNameA = mode.Args[0].MemberName; + return $"TO_NUMBER(TO_CHAR({parameterNameA}, 'WW')) "; + } + public override string BitwiseAnd(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + return string.Format(" BITAND({0},{1}) ", parameter.MemberName, parameter2.MemberName); + } + public override string BitwiseInclusiveOR(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + return string.Format(" BITOR({0},{1}) ", parameter.MemberName, parameter2.MemberName); + } + public override string ParameterKeyWord { get; set; } = ":"; + public override string Modulo(MethodCallExpressionModel model) + { + return " MOD(" + model.Args[0].MemberName + " , " + model.Args[1].MemberName + ")"; + } + public override string GetStringJoinSelector(string result, string separator) + { + if (result.Contains(",")) + { + return $"listagg(to_char({result.Split(',').First()}),'{separator}') within group(order by {result.Split(',').Last()}) "; + } + else + { + return $"listagg(to_char({result}),'{separator}') within group(order by {result}) "; + } + } + public override string HasValue(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format("( {0} IS NOT NULL ) ", parameter.MemberName); + } + + public override string DateDiff(MethodCallExpressionModel model) + { + var parameter = (DateType)(Enum.Parse(typeof(DateType), model.Args[0].MemberValue.ObjToString())); + var begin = model.Args[1].MemberName; + var end = model.Args[2].MemberName; + switch (parameter) + { + case DateType.Year: + return $" ( cast((months_between( {end} , {begin}))/12 as number(9,0) ) )"; + case DateType.Month: + return $" ( cast((months_between( {end} , {begin})) as number(9,0) ) )"; + case DateType.Day: + return $" ( ROUND(TO_NUMBER(cast({end} as date) - cast({begin} as date))) )"; + case DateType.Hour: + return $" ( ROUND(TO_NUMBER(cast({end} as date) - cast({begin} as date)) * 24) )"; + case DateType.Minute: + return $" ( ROUND(TO_NUMBER(cast({end} as date) - cast({begin} as date)) * 24 * 60) )"; + case DateType.Second: + return $" ( ROUND(TO_NUMBER(cast({end} as date) - cast({begin} as date)) * 24 * 60 * 60) )"; + case DateType.Millisecond: + return $" ( ROUND(TO_NUMBER(cast({end} as date) - cast({begin} as date)) * 24 * 60 * 60 * 60) )"; + default: + break; + } + throw new Exception(parameter + " datediff no support"); + } + private void PageEach(IEnumerable pageItems, int pageSize, Action> action) + { + if (pageItems != null && pageItems.Any()) + { + int totalRecord = pageItems.Count(); + int pageCount = (totalRecord + pageSize - 1) / pageSize; + for (int i = 1; i <= pageCount; i++) + { + var list = pageItems.Skip((i - 1) * pageSize).Take(pageSize).ToList(); + action(list); + } + } + } + public override string ContainsArray(MethodCallExpressionModel model) + { + if (model.Args[0].MemberValue == null) + { + return base.ContainsArray(model); + } + var inValueIEnumerable = ((IEnumerable)model.Args[0].MemberValue).Cast().ToArray(); + if (inValueIEnumerable.Count() < 1000) + { + return base.ContainsArray(model); + } + else + { + string result = ""; + PageEach(inValueIEnumerable, 999, it => + { + model.Args.First().MemberValue = it; + result += (base.ContainsArray(model) + " OR "); + + }); + return " ( " + result.TrimEnd(' ').TrimEnd('R').TrimEnd('O') + " ) "; + } + } + public override string ToInt64(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS Number)", parameter.MemberName); + } + + public override string ToTime(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" to_timestamp({0},'0000-01-01 hh24:mi:ss') ", parameter.MemberName); + } + public override string Substring(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + var parameter3 = model.Args[2]; + return string.Format("SUBSTR({0},1 + {1},{2})", parameter.MemberName, parameter2.MemberName, parameter3.MemberName); + } + public override string DateValue(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + var type = (DateType)Enum.Parse(typeof(DateType), parameter2.MemberValue.ObjToString(), false); + switch (type) + { + case DateType.Year: + return string.Format("(CAST(TO_CHAR({0},'yyyy') AS NUMBER))", parameter.MemberName); + case DateType.Month: + return string.Format("(CAST(TO_CHAR({0},'mm') AS NUMBER))", parameter.MemberName); + case DateType.Hour: + return string.Format("(CAST(TO_CHAR({0},'hh24') AS NUMBER))", parameter.MemberName); + case DateType.Second: + return string.Format("(CAST(TO_CHAR({0},'ss') AS NUMBER))", parameter.MemberName); + case DateType.Minute: + return string.Format("(CAST(TO_CHAR({0},'mi') AS NUMBER))", parameter.MemberName); + case DateType.Millisecond: + return string.Format("(CAST(TO_CHAR({0},'ff3') AS NUMBER))", parameter.MemberName); + case DateType.Quarter: + return string.Format("(CAST(TO_CHAR({0},'q') AS NUMBER))", parameter.MemberName); + case DateType.Weekday: + return $" (TO_NUMBER(TO_CHAR({parameter.MemberName}, 'D'))-1) "; + case DateType.Day: + default: + return string.Format("(CAST(TO_CHAR({0},'dd') AS NUMBER))", parameter.MemberName); + } + } + public override string DateAddByType(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + var parameter3 = model.Args[2]; + var type = (DateType)Enum.Parse(typeof(DateType), parameter3.MemberValue.ObjToString(), false); + double time = 1; + switch (type) + { + case DateType.Year: + // 每年 = 12 个月 + return $"ADD_MONTHS({parameter.MemberName}, ({parameter2.MemberName}) * 12)"; + case DateType.Month: + return $"ADD_MONTHS({parameter.MemberName}, {parameter2.MemberName})"; + case DateType.Day: + break; + case DateType.Hour: + time = 1 / 24.0; + break; + case DateType.Second: + time = 1 / 24.0 / 60.0 / 60.0; + break; + case DateType.Minute: + time = 1 / 24.0 / 60.0; + break; + case DateType.Millisecond: + time = 1 / 24.0 / 60.0 / 60.0 / 1000; + break; + } + return string.Format("({0}+({1}*{2})) ", parameter.MemberName, time, parameter2.MemberName); + } + + public override string DateAddDay(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + return string.Format("({0}+(1*{1})) ", parameter.MemberName, parameter2.MemberName); + } + + public override string ToString(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS VARCHAR2(4000))", parameter.MemberName); + } + + public override string ToDecimal(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" CAST({0} AS Number)", parameter.MemberName); + } + + public override string ToDate(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" TO_TIMESTAMP({0}, 'YYYY-MM-DD HH24:MI:SS.FF') ", parameter.MemberName); + } + + public override string ToDateShort(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" TRUNC({0},'dd') ", parameter.MemberName); + } + public override string Contains(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + return string.Format(" ({0} like '%'||{1}||'%') ", parameter.MemberName, parameter2.MemberName); + } + public override string StartsWith(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + return string.Format(" ({0} like {1}||'%') ", parameter.MemberName, parameter2.MemberName); + } + public override string EndsWith(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + return string.Format(" ({0} like '%'||{1}) ", parameter.MemberName, parameter2.MemberName); + } + public override string Trim(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" trim({0}) ", parameter.MemberName); + } + public override string DateIsSameDay(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + return string.Format(" ( cast({0} as date)= cast( {1} as date) ) ", parameter.MemberName, parameter2.MemberName); ; + } + public override string DateIsSameByType(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter2 = model.Args[1]; + var parameter3 = model.Args[2]; + + var dateType = parameter3.MemberValue.ObjToString().ToLower(); + var date1 = parameter.MemberName; + var date2 = parameter2.MemberName; + + if (dateType == "year") + { + return string.Format("(EXTRACT(YEAR FROM {0}) = EXTRACT(YEAR FROM {1}))", date1, date2); + } + else if (dateType == "month") + { + return string.Format("(EXTRACT(YEAR FROM {0}) = EXTRACT(YEAR FROM {1}) AND EXTRACT(MONTH FROM {0}) = EXTRACT(MONTH FROM {1}))", date1, date2); + } + else if (dateType == "day") + { + return string.Format("(TRUNC({0}) = TRUNC({1}))", date1, date2); + } + else if (dateType == "hour") + { + return string.Format("(TRUNC({0}, 'HH24') = TRUNC({1}, 'HH24'))", date1, date2); + } + else if (dateType == "minute") + { + return string.Format("(TRUNC({0}, 'MI') = TRUNC({1}, 'MI'))", date1, date2); + } + else if (dateType == "second") + { + return string.Format("(TRUNC({0}, 'SS') = TRUNC({1}, 'SS'))", date1, date2); + } + else if (dateType == "week" || dateType == "weekday") + { + return string.Format("(TRUNC({0}, 'IW') = TRUNC({1}, 'IW'))", date1, date2); + } + else + { + // 默认按天比较 + return string.Format("(TRUNC({0}) = TRUNC({1}))", date1, date2); + } + } + public override string Length(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + return string.Format(" LENGTH({0}) ", parameter.MemberName); + } + + public override string IsNull(MethodCallExpressionModel model) + { + var parameter = model.Args[0]; + var parameter1 = model.Args[1]; + return string.Format("NVL({0},{1})", parameter.MemberName, parameter1.MemberName); + } + + public override string MergeString(params string[] strings) + { + return string.Join("||", strings); + } + + public override string GetDate() + { + return "systimestamp"; + } + + public override string GetRandom() + { + return "dbms_random.value"; + } + + public override string Collate(MethodCallExpressionModel model) + { + var name = model.Args[0].MemberName; + return $" NLSSORT({0}, 'NLS_SORT = Latin_CI') "; + } + + public override string JsonField(MethodCallExpressionModel model) + { + return $"JSON_VALUE({model.Args[0].MemberName}, '$.{model.Args[1].MemberValue.ToString().ToSqlFilter()}')"; + //"JSON_VALUE(j.kingorder, '$.Id') = '1'"; + } + + public override string CharIndex(MethodCallExpressionModel model) + { + return string.Format("instr ({0},{1},1,1) ", model.Args[0].MemberName, model.Args[1].MemberName); + } + public override string TrimEnd(MethodCallExpressionModel mode) + { + var parameterNameA = mode.Args[0].MemberName; + var parameterNameB = mode.Args[1].MemberName; + return $" RTRIM({parameterNameA}, {parameterNameB}) "; + } + public override string TrimStart(MethodCallExpressionModel mode) + { + + var parameterNameA = mode.Args[0].MemberName; + var parameterNameB = mode.Args[1].MemberName; + return $" LTRIM({parameterNameA}, {parameterNameB}) "; + } + public override string Left(MethodCallExpressionModel mode) + { + var parameterNameA = mode.Args[0].MemberName; + var parameterNameB = mode.Args[1].MemberName; + return $" SUBSTR({parameterNameA}, 1, {parameterNameB}) "; + } + public override string Right(MethodCallExpressionModel mode) + { + var parameterNameA = mode.Args[0].MemberName; + var parameterNameB = mode.Args[1].MemberName; + return $" SUBSTR({parameterNameA}, (LENGTH({parameterNameA})-2), {parameterNameB}) "; + } + + public override string Ceil(MethodCallExpressionModel mode) + { + var parameterNameA = mode.Args[0].MemberName; + return $" CEIL({parameterNameA}) "; + } + + public override string NewUid(MethodCallExpressionModel mode) + { + return " SUBSTR(LOWER(RAWTOHEX(SYS_GUID())), 1, 8) ||\r\n '-' ||\r\n SUBSTR(LOWER(RAWTOHEX(SYS_GUID())), 9, 4) ||\r\n '-' ||\r\n SUBSTR(LOWER(RAWTOHEX(SYS_GUID())), 13, 4) ||\r\n '-' ||\r\n SUBSTR(LOWER(RAWTOHEX(SYS_GUID())), 17, 4) ||\r\n '-' ||\r\n SUBSTR(LOWER(RAWTOHEX(SYS_GUID())), 21) "; + } + public override string FullTextContains(MethodCallExpressionModel mode) + { + var columns = mode.Args[0].MemberName; + if (mode.Args[0].MemberValue is List) + { + columns = "(" + string.Join(",", mode.Args[0].MemberValue as List) + ")"; + } + var searchWord = mode.Args[1].MemberName; + return $" CONTAINS({columns}, {searchWord}, 1) "; + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCFastBuilder.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCFastBuilder.cs new file mode 100644 index 0000000000000000000000000000000000000000..516546ae0be22e876b23f9c59a37f6112a99c714 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCFastBuilder.cs @@ -0,0 +1,174 @@ +using Microsoft.Data.SqlClient; +using Npgsql; +using NpgsqlTypes; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Threading.Tasks; + +namespace SqlSugar.TDSQLForOracleODBC +{ + + public class TDSQLForOracleODBCFastBuilder : FastBuilder, IFastBuilder + { + public static Dictionary PgSqlType = UtilMethods.EnumToDictionary(); + private EntityInfo entityInfo; + + public TDSQLForOracleODBCFastBuilder(EntityInfo entityInfo) + { + this.entityInfo = entityInfo; + } + + public override string UpdateSql { get; set; } = @"UPDATE {1} SET {0} FROM {2} AS TE WHERE {3} +"; + + //public virtual async Task UpdateByTempAsync(string tableName, string tempName, string[] updateColumns, string[] whereColumns) + //{ + // Check.ArgumentNullException(!updateColumns.Any(), "update columns count is 0"); + // Check.ArgumentNullException(!whereColumns.Any(), "where columns count is 0"); + // var sets = string.Join(",", updateColumns.Select(it => $"TM.{it}=TE.{it}")); + // var wheres = string.Join(",", whereColumns.Select(it => $"TM.{it}=TE.{it}")); + // string sql = string.Format(UpdateSql, sets, tableName, tempName, wheres); + // return await this.Context.Ado.ExecuteCommandAsync(sql); + //} + public async Task ExecuteBulkCopyAsync(DataTable dt) + { + List lsColNames = new List(); + for (int i = 0; i < dt.Columns.Count; i++) + { + lsColNames.Add($"\"{dt.Columns[i].ColumnName}\""); + } + string copyString = $"COPY {dt.TableName} ( {string.Join(",", lsColNames)} ) FROM STDIN (FORMAT BINARY)"; + if (this.Context?.CurrentConnectionConfig?.MoreSettings?.DatabaseModel == DbType.OpenGauss) + { + copyString = copyString.Replace("(FORMAT BINARY)", "(FORMAT 'BINARY')"); + } + NpgsqlConnection conn = (NpgsqlConnection)this.Context.Ado.Connection; + var columns = this.Context.DbMaintenance.GetColumnInfosByTableName(this.entityInfo.DbTableName); + try + { + var identityColumnInfo = this.entityInfo.Columns.FirstOrDefault(it => it.IsIdentity); + if (identityColumnInfo != null) + { + throw new Exception("PgSql bulkcopy no support identity"); + } + BulkCopy(dt, copyString, conn, columns); + } + catch (Exception ex) + { + throw ex; + } + finally + { + base.CloseDb(); + } + return await Task.FromResult(dt.Rows.Count); + } + + private void BulkCopy(DataTable dt, string copyString, NpgsqlConnection conn, List columns) + { + if (conn.State == ConnectionState.Closed) + conn.Open(); + List columnViews = new List(); + foreach (DataColumn item in dt.Columns) + { + ColumnView result = new ColumnView(); + result.DbColumnInfo = columns.FirstOrDefault(it => it.DbColumnName.EqualCase(item.ColumnName)); + result.DataColumn = item; + result.EntityColumnInfo = this.entityInfo.Columns.FirstOrDefault(it => it.DbColumnName.EqualCase(item.ColumnName)); + var key = result.DbColumnInfo?.DataType?.ToLower(); + if (result.DbColumnInfo == null) + { + result.Type = null; + } + else if (PgSqlType.ContainsKey(key)) + { + result.Type = PgSqlType[key]; + } + else if (key?.First() == '_') + { + if (key == "_int4") + { + result.Type = NpgsqlDbType.Array | NpgsqlDbType.Integer; + } + else if (key == "_int2") + { + result.Type = NpgsqlDbType.Array | NpgsqlDbType.Smallint; + } + else if (key == "_int8") + { + result.Type = NpgsqlDbType.Array | NpgsqlDbType.Bigint; + } + else if (key == "_float8") + { + result.Type = NpgsqlDbType.Array | NpgsqlDbType.Double; + } + else + { + var type = PgSqlType[key.Substring(1)]; + result.Type = NpgsqlDbType.Array | type; + } + } + else + { + result.Type = null; + } + columnViews.Add(result); + } + using (var writer = conn.BeginBinaryImport(copyString)) + { + foreach (DataRow row in dt.Rows) + { + writer.StartRow(); + foreach (var column in columnViews) + { + var value = row[column.DataColumn.ColumnName]; + if (value == null) + { + value = DBNull.Value; + } + //else if (value is double&&this.Context?.CurrentConnectionConfig?.MoreSettings?.DatabaseModel==null) + //{ + // column.Type = NpgsqlDbType.Double; + //} + if (column.Type == null) + { + writer.Write(value); + } + else + { + writer.Write(value, column.Type.Value); + } + } + } + writer.Complete(); + } + } + + + public override async Task UpdateByTempAsync(string tableName, string tempName, string[] updateColumns, string[] whereColumns) + { + var sqlquerybulder = this.Context.Queryable().SqlBuilder; + Check.ArgumentNullException(!updateColumns.Any(), "update columns count is 0"); + Check.ArgumentNullException(!whereColumns.Any(), "where columns count is 0"); + var sets = string.Join(",", updateColumns.Select(it => $"{sqlquerybulder.GetTranslationColumnName(it)}=TE.{sqlquerybulder.GetTranslationColumnName(it)}")); + var wheres = string.Join(" AND ", whereColumns.Select(it => $"{tableName}.{sqlquerybulder.GetTranslationColumnName(it)}=TE.{sqlquerybulder.GetTranslationColumnName(it)}")); + string sql = string.Format(UpdateSql, sets, tableName, tempName, wheres); + return await this.Context.Ado.ExecuteCommandAsync(sql); + } + public override async Task CreateTempAsync(DataTable dt) + { + await this.Context.Queryable().Where(it => false).AS(dt.TableName).Select(" * into temp mytemptable").ToListAsync(); + dt.TableName = "mytemptable"; + } + + public class ColumnView + { + public DataColumn DataColumn { get; set; } + public EntityColumnInfo EntityColumnInfo { get; set; } + public DbColumnInfo DbColumnInfo { get; set; } + public NpgsqlDbType? Type { get; set; } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCInsertBuilder.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCInsertBuilder.cs new file mode 100644 index 0000000000000000000000000000000000000000..44ac71064936beb78322fb8aa2e0114e2b590460 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCInsertBuilder.cs @@ -0,0 +1,241 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text; + +namespace SqlSugar.TDSQLForOracleODBC +{ + public class TDSQLForOracleODBCInsertBuilder : InsertBuilder + { + public override string SqlTemplate + { + get + { + if (IsReturnIdentity) + { + return @"INSERT INTO {0} + ({1}) + VALUES + ({2}) returning $PrimaryKey"; + } + else + { + return @"INSERT INTO {0} + ({1}) + VALUES + ({2}) ;"; + + } + } + } + public override string SqlTemplateBatch + { + get + { + return "INSERT INTO {0} ({1})"; + } + } + + public override Func ConvertInsertReturnIdFunc { get; set; } = (name, sql) => + { + return sql.Trim().TrimEnd(';') + $"returning {name} "; + }; + public override string ToSqlString() + { + var identities = this.EntityInfo.Columns.Where(it => it.OracleSequenceName.HasValue()).ToList(); + if (IsNoInsertNull) + { + DbColumnInfoList = DbColumnInfoList.Where(it => it.Value != null).ToList(); + } + if (this.Context.CurrentConnectionConfig?.MoreSettings?.EnableOracleIdentity == true) + { + this.DbColumnInfoList = this.DbColumnInfoList.Where(it => it.IsIdentity == false).ToList(); + } + var groupList = DbColumnInfoList.GroupBy(it => it.TableId).ToList(); + var isSingle = groupList.Count() == 1; + string columnsString = string.Join(",", groupList.First().Select(it => Builder.GetTranslationColumnName(it.DbColumnName))); + if (isSingle && this.EntityInfo.EntityName != "Dictionary`2") + { + + string columnParametersString = string.Join(",", this.DbColumnInfoList.Select(it => base.GetDbColumn(it, Builder.SqlParameterKeyWord + it.DbColumnName))); + if (identities.HasValue()) + { + columnsString = columnsString.TrimEnd(',') + "," + string.Join(",", identities.Select(it => Builder.GetTranslationColumnName(it.DbColumnName))); + columnParametersString = columnParametersString.TrimEnd(',') + "," + string.Join(",", identities.Select(it => it.OracleSequenceName + ".nextval")); + } + ActionMinDate(); + return string.Format(SqlTemplate, GetTableNameString, columnsString, columnParametersString); + } + else + { + var bigSize = 500; + if (groupList.Count < bigSize || this.Context?.CurrentConnectionConfig?.MoreSettings?.EnableOracleIdentity == true) + { + string result = Small(identities, groupList, columnsString); + return result; + } + else + { + string result = Big(identities, groupList, columnsString); + return result; + } + } + } + private string Big(List identities, List> groupList, string columnsString) + { + this.Context.Utilities.PageEach(groupList, 100, groupListPasge => + { + this.Parameters = new List(); + var sql = Small(identities, groupListPasge, columnsString); + this.Context.Ado.ExecuteCommand(sql, this.Parameters); + }); + if (identities != null && identities.Count > 0 && this.OracleSeqInfoList != null && this.OracleSeqInfoList.Any()) + { + return $"SELECT {this.OracleSeqInfoList.First().Value - 1} FROM DUAL"; + } + else + { + return $"SELECT {groupList.Count} FROM DUAL"; + } + } + + private string Small(List identities, List> groupList, string columnsString) + { + StringBuilder batchInsetrSql = new StringBuilder(); + batchInsetrSql.AppendLine("INSERT ALL"); + foreach (var item in groupList) + { + batchInsetrSql.Append("INTO " + GetTableNameString + " "); + string insertColumns = ""; + + batchInsetrSql.Append("("); + batchInsetrSql.Append(columnsString); + if (identities.HasValue() && this.IsOffIdentity == false) + { + batchInsetrSql.Append("," + string.Join(",", identities.Select(it => Builder.GetTranslationColumnName(it.DbColumnName)))); + } + batchInsetrSql.Append(") VALUES"); + + + batchInsetrSql.Append("("); + insertColumns = string.Join(",", item.Select(it => GetDbColumn(it, FormatValue(it.Value, it.PropertyName)))); + batchInsetrSql.Append(insertColumns); + if (this.IsOffIdentity == false) + { + if (identities.HasValue()) + { + batchInsetrSql.Append(","); + foreach (var idn in identities) + { + var seqvalue = this.OracleSeqInfoList[idn.OracleSequenceName]; + this.OracleSeqInfoList[idn.OracleSequenceName] = this.OracleSeqInfoList[idn.OracleSequenceName] + 1; + if (identities.Last() == idn) + { + batchInsetrSql.Append(seqvalue); + } + else + { + batchInsetrSql.Append(seqvalue + ","); + } + } + } + } + batchInsetrSql.AppendLine(") "); + + } + if (identities.HasValue()) + { + batchInsetrSql.AppendLine("SELECT " + (this.OracleSeqInfoList.First().Value - 1) + " FROM DUAL"); + } + else + { + batchInsetrSql.AppendLine("SELECT 1 FROM DUAL"); + } + var result = batchInsetrSql.ToString(); + return result; + } + + int i = 0; + public object FormatValue(object value, string name) + { + if (value == null) + { + return "NULL"; + } + else + { + string N = this.Context.GetN(); + var type = UtilMethods.GetUnderType(value.GetType()); + if (type == UtilConstants.StringType && value.ToString().Contains("{SugarSeq:=}")) + { + return value.ToString().Replace("{SugarSeq:=}", ""); + } + if (type == UtilConstants.DateType) + { + var date = value.ObjToDate(); + if (date < UtilMethods.GetMinDate(this.Context.CurrentConnectionConfig)) + { + date = UtilMethods.GetMinDate(this.Context.CurrentConnectionConfig); + } + if (this.Context.CurrentConnectionConfig?.MoreSettings?.DisableMillisecond == true) + { + return "to_date('" + date.ToString("yyyy-MM-dd HH:mm:ss") + "', 'YYYY-MM-DD HH24:MI:SS') "; + } + else + { + return "to_timestamp('" + date.ToString("yyyy-MM-dd HH:mm:ss.ffffff") + "', 'YYYY-MM-DD HH24:MI:SS.FF') "; + } + } + else if (type.IsEnum()) + { + return Convert.ToInt64(value); + } + else if (value is TimeSpan ts) + { + return string.Format( + "INTERVAL '{0} {1:D2}:{2:D2}:{3:D2}.{4:D3}' DAY TO SECOND(3)", + ts.Days, + ts.Hours, + ts.Minutes, + ts.Seconds, + ts.Milliseconds); + } + else if (type == UtilConstants.ByteArrayType) + { + ++i; + var parameterName = this.Builder.SqlParameterKeyWord + name + i; + this.Parameters.Add(new SugarParameter(parameterName, value, System.Data.DbType.Binary)); + return parameterName; + } + else if (type == UtilConstants.BoolType) + { + return value.ObjToBool() ? "1" : "0"; + } + else if (type == UtilConstants.DateTimeOffsetType) + { + var date = UtilMethods.ConvertFromDateTimeOffset((DateTimeOffset)value); + return "to_timestamp('" + date.ToString("yyyy-MM-dd HH:mm:ss.ffffff") + "', 'YYYY-MM-DD HH24:MI:SS.FF') "; + } + else if (type == UtilConstants.StringType || type == UtilConstants.ObjType) + { + if (value.ToString().Length > 1000) + { + ++i; + var parameterName = this.Builder.SqlParameterKeyWord + name + i; + this.Parameters.Add(new SugarParameter(parameterName, value)); + return parameterName; + } + else + { + return N + "'" + value.ToString().ToSqlFilter() + "'"; + } + } + else + { + return N + "'" + value.ToString() + "'"; + } + } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCQueryBuilder.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCQueryBuilder.cs new file mode 100644 index 0000000000000000000000000000000000000000..5b989e94db0381af0ea6940e06f3f6b083f66958 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCQueryBuilder.cs @@ -0,0 +1,137 @@ +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + +namespace SqlSugar.TDSQLForOracleODBC +{ + public class TDSQLForOracleODBCQueryBuilder : QueryBuilder + { + public override bool IsSelectNoAll { get; set; } = true; + public override bool IsComplexModel(string sql) + { + return Regex.IsMatch(sql, @"AS ""\w+\.\w+""") || Regex.IsMatch(sql, @"AS ""\w+\.\w+\.\w+"""); + } + public override string SqlTemplate + { + get + { + return "SELECT {0}{" + UtilConstants.ReplaceKey + "} FROM {1}{2}{3}{4}"; + } + } + public override string ToSqlString() + { + if (this.Offset == "true") + { + return OffsetPage(); + } + var oldTake = Take; + var oldSkip = Skip; + var isDistinctPage = IsDistinct && (Take > 1 || Skip > 1); + if (isDistinctPage) + { + return OffsetPage(); + } + var result = _ToSqlString(); + //if (isDistinctPage) + //{ + // if (this.OrderByValue.HasValue()) + // { + // Take = int.MaxValue; + // result = result.Replace("DISTINCT", $" DISTINCT TOP {int.MaxValue} "); + // } + // Take = oldTake; + // Skip = oldSkip; + // result = this.Context.SqlQueryable(result).Skip(Skip??0).Take(Take??0).ToSql().Key; + + + //} + if (TranLock != null) + { + result = result + TranLock; + } + return result; + } + + private string OffsetPage() + { + var skip = this.Skip ?? 1; + var take = this.Take; + this.Skip = null; + this.Take = null; + this.Offset = null; + var pageSql = $"SELECT * FROM ( SELECT PAGETABLE1.*,ROWNUM PAGEINDEX FROM( {this.ToSqlString()}) PAGETABLE1 WHERE ROWNUM<={skip + take}) WHERE PAGEINDEX>={(skip == 0 ? skip : (skip + 1))}"; + return pageSql; + } + + public string _ToSqlString() + { + string oldOrderBy = this.OrderByValue; + string externalOrderBy = oldOrderBy; + var isIgnoreOrderBy = this.IsCount && this.PartitionByValue.IsNullOrEmpty(); + AppendFilter(); + sql = new StringBuilder(); + if (this.OrderByValue == null && (Skip != null || Take != null)) this.OrderByValue = " ORDER BY " + this.Builder.SqlDateNow + " "; + if (this.PartitionByValue.HasValue()) + { + this.OrderByValue = this.PartitionByValue + this.OrderByValue; + } + var isRowNumber = Skip != null || Take != null; + var rowNumberString = string.Format(",ROW_NUMBER() OVER({0}) AS RowIndex ", GetOrderByString); + string groupByValue = GetGroupByString + HavingInfos; + string orderByValue = (!isRowNumber && this.OrderByValue.HasValue()) ? GetOrderByString : null; + if (isIgnoreOrderBy) { orderByValue = null; } + sql.AppendFormat(SqlTemplate, GetSelectValue, GetTableNameString, GetWhereValueString, groupByValue, orderByValue); + sql.Replace(UtilConstants.ReplaceKey, isRowNumber ? (isIgnoreOrderBy ? null : rowNumberString) : null); + if (isIgnoreOrderBy) { this.OrderByValue = oldOrderBy; return sql.ToString(); } + var result = ToPageSql(sql.ToString(), this.Take, this.Skip); + if (this.GetGroupByString == null && this.Take == 1 && this.Skip == 0 && oldOrderBy == "ORDER BY sysdate ") + { + result = $" {sql.ToString()} {(this.WhereInfos.Any() ? "AND" : "WHERE")} ROWNUM = 1 "; + result = result.Replace(rowNumberString, " "); + } + if (ExternalPageIndex > 0) + { + if (externalOrderBy.IsNullOrEmpty()) + { + externalOrderBy = " ORDER BY " + this.Builder.SqlDateNow + " "; + } + result = string.Format("SELECT ExternalTable.*,ROW_NUMBER() OVER({0}) AS RowIndex2 FROM ({1}) ExternalTable ", GetExternalOrderBy(externalOrderBy), result); + result = ToPageSql2(result, ExternalPageIndex, ExternalPageSize, true); + } + this.OrderByValue = oldOrderBy; + result = GetSqlQuerySql(result); + if (result.IndexOf("-- No table") > 0) + { + return "-- No table"; + } + return result; + } + public override string ToPageSql(string sql, int? take, int? skip, bool isExternal = false) + { + string temp = isExternal ? ExternalPageTempalte : PageTempalte; + if (skip != null && take == null) + { + return string.Format(temp, sql.ToString(), skip.ObjToInt() + 1, long.MaxValue); + } + else if (skip == null && take != null) + { + return string.Format(temp, sql.ToString(), 1, take.ObjToInt()); + } + else if (skip != null && take != null) + { + return string.Format(temp, sql.ToString(), skip.ObjToInt() + 1, skip.ObjToInt() + take.ObjToInt()); + } + else + { + return sql.ToString(); + } + } + + public override string ToPageSql2(string sql, int? pageIndex, int? pageSize, bool isExternal = false) + { + string temp = isExternal ? ExternalPageTempalte : PageTempalte; + return string.Format(temp, sql.ToString(), (pageIndex - 1) * pageSize + 1, pageIndex * pageSize); + } + + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCUpdateBuilder.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCUpdateBuilder.cs new file mode 100644 index 0000000000000000000000000000000000000000..c8c3b68de6bb3e946c3b5e695cff58fb897f14a8 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/SqlBuilder/TDSQLForOracleODBCUpdateBuilder.cs @@ -0,0 +1,292 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text; + +namespace SqlSugar.TDSQLForOracleODBC +{ + public class TDSQLForOracleODBCUpdateBuilder : UpdateBuilder + { + public override string SqlTemplateBatch + { + get + { + return @"UPDATE {1} {2} SET {0} FROM ${{0}} "; + } + } + public override string SqlTemplateJoin + { + get + { + return @" (VALUES + {0} + + ) AS T ({2}) WHERE {1} + "; + } + } + + public override string SqlTemplateBatchUnion + { + get + { + return ","; + } + } + + public object FormatValue(object value, string name, int i, DbColumnInfo columnInfo) + { + if (value == null) + { + return "NULL"; + } + else + { + var type = UtilMethods.GetUnderType(value.GetType()); + if (type == UtilConstants.ByteArrayType || type == UtilConstants.DateType || columnInfo.IsArray || columnInfo.IsJson) + { + var parameterName = this.Builder.SqlParameterKeyWord + name + "_" + i; + var paramter = new SugarParameter(parameterName, value); + if (columnInfo.IsJson) + { + paramter.IsJson = true; + } + if (columnInfo.IsArray) + { + paramter.IsArray = true; + } + this.Parameters.Add(paramter); + return parameterName; + } + else if (type == UtilConstants.DateTimeOffsetType) + { + return FormatDateTimeOffset(value); + } + else if (type == UtilConstants.ByteArrayType) + { + string bytesString = "0x" + BitConverter.ToString((byte[])value); + return bytesString; + } + else if (type.IsEnum()) + { + if (this.Context.CurrentConnectionConfig.MoreSettings?.TableEnumIsString == true) + { + return value.ToSqlValue(); + } + else + { + return Convert.ToInt64(value); + } + } + else if (type == UtilConstants.BoolType) + { + return value.ObjToBool() ? "1" : "0"; + } + else if (type == UtilConstants.StringType || type == UtilConstants.ObjType) + { + return "'" + value.ToString().ToSqlFilter() + "'"; + } + else if (value is decimal v) + { + return v.ToString(CultureInfo.InvariantCulture); + } + else if (value is double dou) + { + return dou.ToString(CultureInfo.InvariantCulture); + } + else + { + return "'" + value.ToString() + "'"; + } + } + } + + protected override string TomultipleSqlString(List> groupList) + { + Check.Exception(PrimaryKeys == null || PrimaryKeys.Count == 0, " Update List need Primary key"); + int pageSize = 200; + int pageIndex = 1; + int totalRecord = groupList.Count; + int pageCount = (totalRecord + pageSize - 1) / pageSize; + StringBuilder batchUpdateSql = new StringBuilder(); + while (pageCount >= pageIndex) + { + StringBuilder updateTable = new StringBuilder(); + string setValues = string.Join(",", groupList.First().Where(it => it.IsPrimarykey == false && (it.IsIdentity == false || (IsOffIdentity && it.IsIdentity))).Select(it => + { + if (SetValues.IsValuable()) + { + var setValue = SetValues.Where(sv => sv.Key == Builder.GetTranslationColumnName(it.DbColumnName)); + if (setValue != null && setValue.Any()) + { + return setValue.First().Value; + } + } + var result = string.Format("{0}=T.{0}", Builder.GetTranslationColumnName(it.DbColumnName)); + return result; + })); + string tempColumnValue = string.Join(",", groupList.First().Select(it => + { + if (SetValues.IsValuable()) + { + var setValue = SetValues.Where(sv => sv.Key == Builder.GetTranslationColumnName(it.DbColumnName)); + if (setValue != null && setValue.Any()) + { + return setValue.First().Value; + } + } + var result = Builder.GetTranslationColumnName(it.DbColumnName); + return result; + })); + batchUpdateSql.AppendFormat(SqlTemplateBatch.ToString(), setValues, GetTableNameStringNoWith, TableWithString); + int i = 0; + var tableColumnList = this.Context.DbMaintenance.GetColumnInfosByTableName(GetTableNameStringNoWith); + + foreach (var columns in groupList.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList()) + { + var isFirst = i == 0; + if (!isFirst) + { + updateTable.Append(SqlTemplateBatchUnion); + } + updateTable.Append("\r\n (" + string.Join(",", columns.Select(it => + { + var columnInfo = tableColumnList.FirstOrDefault(x => x.DbColumnName.Equals(it.DbColumnName, StringComparison.OrdinalIgnoreCase)); + var dbType = columnInfo?.DataType; + if (dbType == null) + { + var typeName = it.PropertyType.Name.ToLower(); + if (columnInfo == null && it.PropertyType.IsEnum) + { + if (this.Context.CurrentConnectionConfig?.MoreSettings?.TableEnumIsString != true) + { + typeName = "int"; + } + } + if (typeName == "int32") + typeName = "int"; + if (typeName == "int64") + typeName = "long"; + if (typeName == "int16") + typeName = "short"; + if (typeName == "boolean") + typeName = "bool"; + + var isAnyType = PostgreSQLDbBind.MappingTypesConst.Where(x => x.Value.ToString().ToLower() == typeName).Any(); + if (isAnyType) + { + dbType = PostgreSQLDbBind.MappingTypesConst.Where(x => x.Value.ToString().ToLower() == typeName).FirstOrDefault().Key; + } + else + { + dbType = "varchar"; + } + } + if (it?.PropertyType?.FullName == "NetTopologySuite.Geometries.Geometry") + { + return string.Format(" {0} ", base.GetDbColumn(it, FormatValue(it.Value, it.DbColumnName, i + (pageIndex - 1) * 100000, it)), dbType); + } + return string.Format("CAST({0} AS {1})", base.GetDbColumn(it, FormatValue(it.Value, it.DbColumnName, i + (pageIndex - 1) * 100000, it)), dbType); + + })) + ")"); + ++i; + } + pageIndex++; + updateTable.Append("\r\n"); + string whereString = null; + if (this.WhereValues.HasValue()) + { + foreach (var item in WhereValues) + { + var isFirst = whereString == null; + whereString += (isFirst ? null : " AND "); + whereString += item; + } + } + else if (PrimaryKeys.HasValue()) + { + foreach (var item in PrimaryKeys) + { + var isFirst = whereString == null; + whereString += (isFirst ? null : " AND "); + whereString += string.Format("{0}.{1}=T.{1}", GetTableNameStringNoWith, Builder.GetTranslationColumnName(item)); + } + } + var format = string.Format(SqlTemplateJoin, updateTable, whereString, tempColumnValue); + batchUpdateSql.Replace("${0}", format); + batchUpdateSql.Append(";"); + } + batchUpdateSql = GetBatchUpdateSql(batchUpdateSql); + return batchUpdateSql.ToString(); + } + + private StringBuilder GetBatchUpdateSql(StringBuilder batchUpdateSql) + { + if (ReSetValueBySqlExpListType == null && ReSetValueBySqlExpList != null) + { + var result = batchUpdateSql.ToString(); + foreach (var item in ReSetValueBySqlExpList) + { + var dbColumnName = item.Value.DbColumnName; + if (item.Value.Type == ReSetValueBySqlExpListModelType.List) + { + result = result.Replace($"{dbColumnName}=T.{dbColumnName}", $"{dbColumnName}={GetTableNameString}.{dbColumnName}{item.Value.Sql}T.{dbColumnName}"); + } + else + { + if (item.Value?.Sql?.StartsWith("( CASE WHEN") == true) + { + result = result.Replace($"{dbColumnName}=T.{dbColumnName}", $"{dbColumnName}={item.Value.Sql.Replace(" \"", $" {Builder.GetTranslationColumnName(this.TableName)}.\"")}"); + } + else + { + result = result.Replace($"{dbColumnName}=T.{dbColumnName}", $"{dbColumnName}={item.Value.Sql.Replace(dbColumnName, $"{Builder.GetTranslationColumnName(this.TableName)}.{dbColumnName}")}"); + } + } + batchUpdateSql = new StringBuilder(result); + } + } + + return batchUpdateSql; + } + protected override string GetJoinUpdate(string columnsString, ref string whereString) + { + if (this.JoinInfos?.Count > 1) + { + return this.GetJoinUpdateMany(columnsString, whereString); + } + var formString = $" {Builder.GetTranslationColumnName(this.TableName)} AS {Builder.GetTranslationColumnName(this.ShortName)} "; + var joinString = ""; + foreach (var item in this.JoinInfos) + { + whereString += " AND " + item.JoinWhere; + joinString += $"\r\n FROM {Builder.GetTranslationColumnName(item.TableName)} {Builder.GetTranslationColumnName(item.ShortName)} "; + } + var tableName = formString + "\r\n "; + columnsString = columnsString.Replace(Builder.GetTranslationColumnName(this.ShortName) + ".", "") + joinString; + return string.Format(SqlTemplate, tableName, columnsString, whereString); + } + private string GetJoinUpdateMany(string columnsString, string where) + { + var formString = $" {Builder.GetTranslationColumnName(this.TableName)} AS {Builder.GetTranslationColumnName(this.ShortName)} "; + var joinString = ""; + var i = 0; + foreach (var item in this.JoinInfos) + { + var whereString = " ON " + item.JoinWhere; + joinString += $"\r\n JOIN {Builder.GetTranslationColumnName(item.TableName)} {Builder.GetTranslationColumnName(item.ShortName)} "; + joinString = joinString + whereString; + i++; + } + var tableName = Builder.GetTranslationColumnName(this.TableName) + "\r\n "; + columnsString = columnsString.Replace(Builder.GetTranslationColumnName(this.ShortName) + ".", "") + $" FROM {Builder.GetTranslationColumnName(this.TableName)} {Builder.GetTranslationColumnName(this.ShortName)}\r\n " + joinString; + return string.Format(SqlTemplate, tableName, columnsString, where); + } + public override string FormatDateTimeOffset(object value) + { + return "'" + ((DateTimeOffset)value).ToString("o") + "'"; + } + } +} + diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/TDSQLForOracleODBCProvider.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/TDSQLForOracleODBCProvider.cs new file mode 100644 index 0000000000000000000000000000000000000000..fd5cbbc4be8d3b2f7eb121ecd93b801c8a4d6907 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/TDSQLForOracleODBC/TDSQLForOracleODBCProvider.cs @@ -0,0 +1,364 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.Odbc; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +namespace SqlSugar.TDSQLForOracleODBC +{ + public class TDSQLForOracleODBCProvider : AdoProvider + { + public override string SqlParameterKeyWord { get { return ":"; } } + public TDSQLForOracleODBCProvider() { } + public override IDbConnection Connection + { + get + { + if (base._DbConnection == null) + { + try + { + base._DbConnection = new OdbcConnection(base.Context.CurrentConnectionConfig.ConnectionString); + } + catch (Exception ex) + { + throw ex; + } + } + return base._DbConnection; + } + set + { + base._DbConnection = value; + } + } + + public string SplitCommandTag => UtilConstants.ReplaceCommaKey.Replace("{", "").Replace("}", ""); + + + public override object GetScalar(string sql, params SugarParameter[] parameters) + { + if (this.Context.Ado.Transaction != null) + { + return _GetScalar(sql, parameters); + } + else + { + try + { + this.Context.Ado.BeginTran(); + var result = _GetScalar(sql, parameters); + this.Context.Ado.CommitTran(); + return result; + } + catch (Exception ex) + { + this.Context.Ado.RollbackTran(); + throw ex; + } + } + } + + public override async Task GetScalarAsync(string sql, params SugarParameter[] parameters) + { + if (this.Context.Ado.Transaction != null) + { + return await _GetScalarAsync(sql, parameters); + } + else + { + try + { + this.Context.Ado.BeginTran(); + var result = await _GetScalarAsync(sql, parameters); + this.Context.Ado.CommitTran(); + return result; + } + catch (Exception ex) + { + this.Context.Ado.RollbackTran(); + throw ex; + } + } + } + private object _GetScalar(string sql, SugarParameter[] parameters) + { + if (sql == null) throw new Exception("sql is null"); + if (sql.IndexOf(this.SplitCommandTag) > 0) + { + var sqlParts = Regex.Split(sql, this.SplitCommandTag).Where(it => !string.IsNullOrEmpty(it)).ToList(); + object result = 0; + foreach (var item in sqlParts) + { + if (item.TrimStart('\r').TrimStart('\n') != "") + { + result = base.GetScalar(item, parameters); + } + } + return result; + } + else + { + return base.GetScalar(sql, parameters); + } + } + private async Task _GetScalarAsync(string sql, SugarParameter[] parameters) + { + if (sql == null) throw new Exception("sql is null"); + if (sql.IndexOf(this.SplitCommandTag) > 0) + { + var sqlParts = Regex.Split(sql, this.SplitCommandTag).Where(it => !string.IsNullOrEmpty(it)).ToList(); + object result = 0; + foreach (var item in sqlParts) + { + if (item.TrimStart('\r').TrimStart('\n') != "") + { + result = await base.GetScalarAsync(item, parameters); + } + } + return result; + } + else + { + return await base.GetScalarAsync(sql, parameters); + } + } + + public override int ExecuteCommand(string sql, SugarParameter[] parameters) + { + if (sql == null) throw new Exception("sql is null"); + if (sql.IndexOf(this.SplitCommandTag) > 0) + { + var sqlParts = Regex.Split(sql, this.SplitCommandTag).Where(it => !string.IsNullOrEmpty(it)).ToList(); + int result = 0; + foreach (var item in sqlParts) + { + if (item.TrimStart('\r').TrimStart('\n') != "") + { + result += base.ExecuteCommand(item, parameters); + } + } + return result; + } + else + { + return base.ExecuteCommand(sql, parameters); + } + } + public override async Task ExecuteCommandAsync(string sql, SugarParameter[] parameters) + { + if (sql == null) throw new Exception("sql is null"); + if (sql.IndexOf(this.SplitCommandTag) > 0) + { + var sqlParts = Regex.Split(sql, this.SplitCommandTag).Where(it => !string.IsNullOrEmpty(it)).ToList(); + int result = 0; + foreach (var item in sqlParts) + { + if (item.TrimStart('\r').TrimStart('\n') != "") + { + result += await base.ExecuteCommandAsync(item, parameters); + } + } + return result; + } + else + { + return base.ExecuteCommand(sql, parameters); + } + } + + /// + /// Only Odbc + /// + /// + public override void BeginTran(string transactionName) + { + CheckConnection(); + base.Transaction = ((OdbcConnection)this.Connection).BeginTransaction(); + } + /// + /// Only Odbc + /// + /// + /// + public override void BeginTran(IsolationLevel iso, string transactionName) + { + CheckConnection(); + base.Transaction = ((OdbcConnection)this.Connection).BeginTransaction(iso); + } + + public override IDataAdapter GetAdapter() + { + return new TDSQLForOracleDataAdapter(); + } + public override DbCommand GetCommand(string sql, SugarParameter[] parameters) + { + var helper = new TDSQLForOracleODBCInsertBuilder(); + helper.Context = this.Context; + List orderParameters = new List(); + if (parameters.HasValue()) + { + foreach (var p in parameters) + { + if (!p.ParameterName.StartsWith(this.SqlParameterKeyWord)) + { + p.ParameterName = this.SqlParameterKeyWord + p.ParameterName; + } + } + orderParameters = parameters.Where(it => sql.Contains(it.ParameterName)) + .Select(it => new { p = it, sort = GetSortId(sql, it) }) + .OrderBy(it => it.sort) + .Where(it => it.sort != 0) + .Select(it => it.p) + .ToList(); + foreach (var param in parameters.OrderByDescending(it => it.ParameterName.Length)) + { + sql = sql.Replace(param.ParameterName, "?"); + } + + } + OdbcCommand sqlCommand = new OdbcCommand(sql, (OdbcConnection)this.Connection); + sqlCommand.CommandType = this.CommandType; + sqlCommand.CommandTimeout = this.CommandTimeOut; + if (this.Transaction != null) + { + sqlCommand.Transaction = (OdbcTransaction)this.Transaction; + } + if (orderParameters.HasValue()) + { + OdbcParameter[] ipars = GetSqlParameter(orderParameters.ToArray()); + sqlCommand.Parameters.AddRange(ipars); + } + CheckConnection(); + return sqlCommand; + } + + private static int GetSortId(string sql, SugarParameter it) + { + return new List() { + 0, + sql.IndexOf(it.ParameterName+")"), + sql.IndexOf(it.ParameterName+" "), + sql.IndexOf(it.ParameterName+"="), + sql.IndexOf(it.ParameterName+"+"), + sql.IndexOf(it.ParameterName+"-"), + sql.IndexOf(it.ParameterName+";"), + sql.IndexOf(it.ParameterName+","), + sql.IndexOf(it.ParameterName+"*"), + sql.IndexOf(it.ParameterName+"/"), + sql.IndexOf(it.ParameterName+"|"), + sql.IndexOf(it.ParameterName+"&"), + sql.EndsWith(it.ParameterName)?sql.IndexOf(it.ParameterName):0 + }.Max(); + } + + public override void SetCommandToAdapter(IDataAdapter dataAdapter, DbCommand command) + { + ((TDSQLForOracleDataAdapter)dataAdapter).SelectCommand = (OdbcCommand)command; + } + /// + /// if mysql return MySqlParameter[] pars + /// if sqlerver return SqlParameter[] pars ... + /// + /// + /// + public override IDataParameter[] ToIDbDataParameter(params SugarParameter[] parameters) + { + if (parameters == null || parameters.Length == 0) return new OdbcParameter[] { }; + OdbcParameter[] result = new OdbcParameter[parameters.Length]; + int index = 0; + foreach (var parameter in parameters) + { + if (parameter.Value == null) parameter.Value = DBNull.Value; + var sqlParameter = new OdbcParameter(); + sqlParameter.ParameterName = parameter.ParameterName; + //sqlParameter.UdtTypeName = parameter.UdtTypeName; + sqlParameter.Size = parameter.Size; + sqlParameter.Value = parameter.Value; + sqlParameter.DbType = parameter.DbType; + sqlParameter.Direction = parameter.Direction; + result[index] = sqlParameter; + if (sqlParameter.Direction.IsIn(ParameterDirection.Output, ParameterDirection.InputOutput, ParameterDirection.ReturnValue)) + { + if (this.OutputParameters == null) this.OutputParameters = new List(); + this.OutputParameters.RemoveAll(it => it.ParameterName == sqlParameter.ParameterName); + this.OutputParameters.Add(sqlParameter); + } + ++index; + } + return result; + } + /// + /// if mysql return MySqlParameter[] pars + /// if sqlerver return SqlParameter[] pars ... + /// + /// + /// + public OdbcParameter[] GetSqlParameter(params SugarParameter[] parameters) + { + if (parameters == null || parameters.Length == 0) return null; + OdbcParameter[] result = new OdbcParameter[parameters.Length]; + int index = 0; + foreach (var parameter in parameters) + { + if (parameter.Value == null) parameter.Value = DBNull.Value; + var sqlParameter = new OdbcParameter(); + sqlParameter.ParameterName = parameter.ParameterName; + //sqlParameter.UdtTypeName = parameter.UdtTypeName; + sqlParameter.Size = parameter.Size; + sqlParameter.Value = parameter.Value; + sqlParameter.DbType = GetDbType(parameter); + var isTime = parameter.DbType == System.Data.DbType.Time; + if (isTime) + { + sqlParameter.Value = DateTime.Parse(parameter.Value?.ToString()).TimeOfDay; + } + if (sqlParameter.Value != null && sqlParameter.Value != DBNull.Value && sqlParameter.DbType == System.Data.DbType.DateTime) + { + var date = Convert.ToDateTime(sqlParameter.Value); + if (date == DateTime.MinValue) + { + sqlParameter.Value = UtilMethods.GetMinDate(this.Context.CurrentConnectionConfig); + } + } + if (parameter.Direction == 0) + { + parameter.Direction = ParameterDirection.Input; + } + sqlParameter.Direction = parameter.Direction; + result[index] = sqlParameter; + if (sqlParameter.Direction.IsIn(ParameterDirection.Output, ParameterDirection.InputOutput, ParameterDirection.ReturnValue)) + { + if (this.OutputParameters == null) this.OutputParameters = new List(); + this.OutputParameters.RemoveAll(it => it.ParameterName == sqlParameter.ParameterName); + this.OutputParameters.Add(sqlParameter); + } + + ++index; + } + return result; + } + + private static System.Data.DbType GetDbType(SugarParameter parameter) + { + if (parameter.DbType == System.Data.DbType.UInt16) + { + return System.Data.DbType.Int16; + } + else if (parameter.DbType == System.Data.DbType.UInt32) + { + return System.Data.DbType.Int32; + } + else if (parameter.DbType == System.Data.DbType.UInt64) + { + return System.Data.DbType.Int64; + } + else + { + return parameter.DbType; + } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/ErrorMessage.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/ErrorMessage.cs new file mode 100644 index 0000000000000000000000000000000000000000..02350c782912092203c2df78755ec20ebd14adcf --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/ErrorMessage.cs @@ -0,0 +1,61 @@ +using System.Collections.Generic; +namespace SqlSugar.TDSQLForOracleODBC +{ + internal static partial class ErrorMessage + { + internal static LanguageType SugarLanguageType { get; set; } = LanguageType.Default; + internal static string ObjNotExist + { + get + { + return GetThrowMessage("{0} does not exist.", + "{0}不存在。"); + } + } + internal static string EntityMappingError + { + get + { + return GetThrowMessage("Entity mapping error.{0}", + "实体与表映射出错。{0}"); + } + } + + public static string NotSupportedDictionary + { + get + { + return GetThrowMessage("This type of Dictionary is not supported for the time being. You can try Dictionary, or contact the author!!", + "暂时不支持该类型的Dictionary 你可以试试 Dictionary或者联系作者!!"); + } + } + + public static string NotSupportedArray + { + get + { + return GetThrowMessage("This type of Array is not supported for the time being. You can try object[] or contact the author!!", + "暂时不支持该类型的Array 你可以试试 object[] 或者联系作者!!"); + } + } + + internal static string GetThrowMessage(string enMessage, string cnMessage, params string[] args) + { + if (SugarLanguageType == LanguageType.Default) + { + List formatArgs = new List() { enMessage, cnMessage }; + formatArgs.AddRange(args); + return string.Format(@"中文提示 : {1} +English Message : {0}", formatArgs.ToArray()); + } + else if (SugarLanguageType == LanguageType.English) + { + return enMessage; + } + else + { + return cnMessage; + } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/ExpressionConst.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/ExpressionConst.cs new file mode 100644 index 0000000000000000000000000000000000000000..7dab58fc4a9f5b80a8e3250492ced2635d5fd16e --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/ExpressionConst.cs @@ -0,0 +1,14 @@ +namespace SqlSugar.TDSQLForOracleODBC +{ + internal class ExpressionConst + { + public const string Const = "Const"; + public const string FormatSymbol = "{0}"; + public const string RightParenthesis = ")"; + public const string LeftParenthesis = "("; + public const string MethodConst = "MethodConst"; + public const string SqlFuncFullName = "SqlSugar.SqlFunc"; + public const string BinaryFormatString = " ( {0} {1} {2} ) "; + public const string ExpressionReplace = "46450BDC-77B7-4025-B2A6-3F048CA85AD0"; + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/FileHelper.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/FileHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..2e8e3d73939be61e9d38288440383d859ed9deaa --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/FileHelper.cs @@ -0,0 +1,68 @@ +using System; +using System.IO; +using System.Text; + +namespace SqlSugar.TDSQLForOracleODBC +{ + internal class FileHelper + { + public static void CreateFile(string filePath, string text, Encoding encoding) + { + try + { + if (IsExistFile(filePath)) + { + DeleteFile(filePath); + } + if (!IsExistFile(filePath)) + { + string directoryPath = GetDirectoryFromFilePath(filePath); + CreateDirectory(directoryPath); + + //Create File + FileInfo file = new FileInfo(filePath); + using (FileStream stream = file.Create()) + { + using (StreamWriter writer = new StreamWriter(stream, encoding)) + { + writer.Write(text); + writer.Flush(); + } + } + } + } + catch (Exception ex) + { + throw ex; + } + } + public static bool IsExistDirectory(string directoryPath) + { + return Directory.Exists(directoryPath); + } + public static void CreateDirectory(string directoryPath) + { + if (!IsExistDirectory(directoryPath)) + { + Directory.CreateDirectory(directoryPath); + } + } + public static void DeleteFile(string filePath) + { + if (IsExistFile(filePath)) + { + File.Delete(filePath); + } + } + public static string GetDirectoryFromFilePath(string filePath) + { + FileInfo file = new FileInfo(filePath); + DirectoryInfo directory = file.Directory; + return directory.FullName; + } + public static bool IsExistFile(string filePath) + { + return File.Exists(filePath); + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/QueryableFormat.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/QueryableFormat.cs new file mode 100644 index 0000000000000000000000000000000000000000..c2a2c83d25883e9500f3dd8d6366a722d7a96665 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/QueryableFormat.cs @@ -0,0 +1,15 @@ +using System; +using System.Reflection; + +namespace SqlSugar.TDSQLForOracleODBC +{ + internal class QueryableFormat + { + public Type Type { get; set; } + public string TypeString { get; set; } + public string Format { get; set; } + public string PropertyName { get; set; } + public string MethodName { get; set; } + public MethodInfo MethodInfo { get; set; } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/UtilConstants.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/UtilConstants.cs new file mode 100644 index 0000000000000000000000000000000000000000..bf84c3b70502e065cccbeaeb9744d4de10e009bc --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/UtilConstants.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Generic; +using System.Dynamic; +using System.Linq.Expressions; +namespace SqlSugar.TDSQLForOracleODBC +{ + internal static class UtilConstants + { + public const string Dot = "."; + public const char DotChar = '.'; + internal const string Space = " "; + internal const char SpaceChar = ' '; + internal const string AssemblyName = "SqlSugar.TDSQLForOracleODBC"; + internal static string ReplaceKey = "{" + Guid.NewGuid() + "}"; + internal const string ReplaceCommaKey = "{112A689B-17A1-4A06-9D27-A39EAB8B4SDF}"; + internal const string GroupReplaceKey = "{GroupReplaceKey_l33asdysaas1231s}"; + + internal static Type UShortType = typeof(ushort); + internal static Type ULongType = typeof(ulong); + internal static Type UIntType = typeof(uint); + internal static Type IntType = typeof(int); + internal static Type LongType = typeof(long); + internal static Type GuidType = typeof(Guid); + internal static Type BoolType = typeof(bool); + internal static Type BoolTypeNull = typeof(bool?); + internal static Type ByteType = typeof(Byte); + internal static Type SByteType = typeof(sbyte); + internal static Type ObjType = typeof(object); + internal static Type DobType = typeof(double); + internal static Type FloatType = typeof(float); + internal static Type ShortType = typeof(short); + internal static Type DecType = typeof(decimal); + internal static Type StringType = typeof(string); + internal static Type DateType = typeof(DateTime); + internal static Type DateTimeOffsetType = typeof(DateTimeOffset); + internal static Type TimeSpanType = typeof(TimeSpan); + internal static Type ByteArrayType = typeof(byte[]); + internal static Type ModelType = typeof(ModelContext); + internal static Type DynamicType = typeof(ExpandoObject); + internal static Type Dicii = typeof(KeyValuePair); + internal static Type DicIS = typeof(KeyValuePair); + internal static Type DicSi = typeof(KeyValuePair); + internal static Type DicSS = typeof(KeyValuePair); + internal static Type DicOO = typeof(KeyValuePair); + internal static Type DicSo = typeof(KeyValuePair); + internal static Type DicArraySS = typeof(Dictionary); + internal static Type DicArraySO = typeof(Dictionary); + + public static Type SqlConvertType = typeof(SqlSugar.DbConvert.NoParameterCommonPropertyConvert); + + public static Type SugarType = typeof(SqlSugarProvider); + + + internal static Type[] NumericalTypes = new Type[] + { + typeof(int), + typeof(uint), + typeof(byte), + typeof(sbyte), + typeof(long), + typeof(ulong), + typeof(short), + typeof(ushort), + }; + //internal static CultureInfo EnCultureInfo = new CultureInfo("en"); + + internal static string[] DateTypeStringList = new string[] + { + "Year", + "Month", + "Day", + "Hour", + "Second" , + "Minute", + "Millisecond", + "Date" + }; + + public static ConstantExpression ExpTrue = Expression.Constant(true); + public static ConstantExpression ExpFalse = Expression.Constant(false); + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/UtilExtensions.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/UtilExtensions.cs new file mode 100644 index 0000000000000000000000000000000000000000..002b8a77259804c3a051995e0fd86fe01be43f38 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/UtilExtensions.cs @@ -0,0 +1,33 @@ +namespace SqlSugar.TDSQLForOracleODBC +{ + /// + ///Common Extensions for external users + /// + public static class UtilExtensions + { + public static string ToLower(this string value, bool isLower) + { + if (isLower) + { + return value.ObjToString().ToLower(); + } + return value.ObjToString(); + } + public static string ToUpper(this string value, bool isAutoToUpper) + { + if (value == null) return null; + if (isAutoToUpper == false) return value; + return value.ToUpper(); + } + + public static string GetN(this SqlSugarProvider Context) + { + var N = "N"; + if (Context.CurrentConnectionConfig.MoreSettings != null && Context.CurrentConnectionConfig.MoreSettings.DisableNvarchar) + { + N = ""; + } + return N; + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/UtilMethods.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/UtilMethods.cs new file mode 100644 index 0000000000000000000000000000000000000000..93a4b05537683b87859ed1665d9a809cffd1246f --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/UtilMethods.cs @@ -0,0 +1,1915 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; + +namespace SqlSugar.TDSQLForOracleODBC +{ + public class UtilMethods + { + public static string EscapeLikeValue(ISqlSugarClient db, string value, char wildcard = '%') + { + var dbType = db.CurrentConnectionConfig.DbType; + if (db.CurrentConnectionConfig?.MoreSettings?.DatabaseModel != null) + { + dbType = db.CurrentConnectionConfig.MoreSettings.DatabaseModel.Value; + } + if (string.IsNullOrEmpty(value)) + return value; + + string wildcardStr = wildcard.ToString(); + + switch (dbType) + { + // 支持标准 SQL LIKE 转义,通常使用中括号 [] 或反斜杠 \ 进行转义 + case DbType.SqlServer: + case DbType.Access: + case DbType.Odbc: + case DbType.TDSQLForPGODBC: + case DbType.TDSQLForOracleODBC: + // SQL Server 使用中括号转义 %, _ 等 + value = value.Replace("[", "[[]") + .Replace("]", "[]]") + .Replace(wildcardStr, $"[{wildcard}]"); + break; + + // PostgreSQL 风格数据库,使用反斜杠进行 LIKE 转义 + case DbType.PostgreSQL: + case DbType.OpenGauss: + case DbType.TDSQL: + case DbType.GaussDB: + case DbType.GaussDBNative: + // MySQL 和兼容库,使用反斜杠进行转义 + case DbType.MySql: + case DbType.MySqlConnector: + case DbType.Tidb: + case DbType.PolarDB: + case DbType.OceanBase: + case DbType.Oracle: + case DbType.OceanBaseForOracle: + case DbType.HG: + case DbType.Dm: + case DbType.GBase: + case DbType.DB2: + case DbType.HANA: + case DbType.GoldenDB: + case DbType.Sqlite: + case DbType.DuckDB: + case DbType.QuestDB: + case DbType.Doris: + case DbType.Xugu: + case DbType.Vastbase: + default: + value = value + .Replace(wildcardStr, "\\\\" + wildcard); + break; + } + + return value; + } + + + public static List CopySugarParameters(List pars) + { + if (pars == null) return null; + var newParameters = pars.Select(it => new SugarParameter(it.ParameterName, it.Value) + { + TypeName = it.TypeName, + Value = it.Value, + IsRefCursor = it.IsRefCursor, + IsArray = it.IsArray, + IsJson = it.IsJson, + ParameterName = it.ParameterName, + IsNvarchar2 = it.IsNvarchar2, + IsNClob = it.IsClob, + IsClob = it.IsClob, + UdtTypeName = it.UdtTypeName, + CustomDbType = it.CustomDbType, + DbType = it.DbType, + Direction = it.Direction, + Precision = it.Precision, + Size = it.Size, + Scale = it.Scale, + IsNullable = it.IsNullable, + SourceColumn = it.SourceColumn, + SourceColumnNullMapping = it.SourceColumnNullMapping, + SourceVersion = it.SourceVersion, + TempDate = it.TempDate, + _Size = it._Size + }); + return newParameters.ToList(); + } + public static bool IsTuple(Type tType, List classProperties) + { + if (classProperties?.Any() != true) + { + return false; + } + return tType.FullName?.StartsWith("System.Tuple`") == true && classProperties.FirstOrDefault()?.Name == "Item1"; + } + + internal static string GetTableByDbLink(SqlSugarProvider context, string tableName, string oldTableName, TenantAttribute attr) + { + QueryBuilder queryBuilder = InstanceFactory.GetQueryBuilderWithContext(context); + var dbLinkName = context.Root.GetConnection(attr.configId).CurrentConnectionConfig.DbLinkName; + if (dbLinkName != null) + { + if (dbLinkName.First() == '@') + { + tableName = queryBuilder.Builder.GetTranslationColumnName(oldTableName) + dbLinkName; + } + else if (dbLinkName.Last() == '_') + { + tableName = dbLinkName + oldTableName; + } + else + { + tableName = dbLinkName + "." + queryBuilder.Builder.GetTranslationColumnName(oldTableName); + } + } + return tableName; + } + public static List> GetColumnInfo(IDataReader reader) + { + var columnInfo = new List>(); + + // 获取列的数量 + int columnCount = reader.FieldCount; + + // 遍历每一列 + for (int i = 0; i < columnCount; i++) + { + // 获取列名 + string columnName = reader.GetName(i); + + // 获取列的数据类型 + Type columnType = reader.GetFieldType(i); + + // 将列名和类型添加到列表中 + columnInfo.Add(Tuple.Create(columnName, columnType)); + } + + return columnInfo; + } + public static object ConvertToObjectList(Type targetType, List sourceList) + { + // 创建 List 类型的实例 + object resultList = Activator.CreateInstance(typeof(List<>).MakeGenericType(targetType)); + // 获取 Add 方法 + var addMethod = resultList.GetType().GetMethod("Add"); + foreach (var obj in sourceList) + { + addMethod.Invoke(resultList, new object[] { obj }); + } + return resultList; + } + public static Dictionary DataRowToDictionary(DataRow row) + { + Dictionary dictionary = new Dictionary(); + + // 遍历所有列并将其添加到字典中 + foreach (DataColumn column in row.Table.Columns) + { + if (column.ColumnName != "Items" && column.DataType.Name.IsCollectionsList() == false) + { + dictionary.Add(column.ColumnName, row[column]); + } + } + + return dictionary; + } + public static IEnumerable BuildTree(ISqlSugarClient db, IEnumerable list, string idName, string pIdName, string childName, object rootValue) + { + var entityInfo = db.EntityMaintenance.GetEntityInfo(); ; + var mainIdProp = entityInfo.Type.GetProperty(idName); + var pIdProp = entityInfo.Type.GetProperty(pIdName); + var childProp = entityInfo.Type.GetProperty(childName); + + Dictionary kvList; + IEnumerable> group; + BuildTreeGroup(list, mainIdProp, pIdProp, out kvList, out group); + + var root = rootValue != null ? group.FirstOrDefault(x => x.Key == rootValue.ObjToString()) : group.FirstOrDefault(x => x.Key == null || x.Key == "" || x.Key == "0" || x.Key == Guid.Empty.ToString()); + + if (root != null) + { + foreach (var item in group) + { + if (kvList.TryGetValue(item.Key, out var parent)) + { + childProp.SetValue(parent, item.ToList()); + } + } + } + + return root; + } + + private static void BuildTreeGroup(IEnumerable list, PropertyInfo mainIdProp, PropertyInfo pIdProp, out Dictionary kvList, out IEnumerable> group) + { + kvList = list.ToDictionary(x => mainIdProp.GetValue(x).ObjToString()); + group = list.GroupBy(x => pIdProp.GetValue(x).ObjToString()); + } + + internal static bool? _IsErrorDecimalString { get; set; } + internal static bool? IsErrorDecimalString() + { + if (_IsErrorDecimalString == null) + { + decimal dec = Convert.ToDecimal(1.1); + _IsErrorDecimalString = dec.ToString().Contains(","); + } + return _IsErrorDecimalString; + } + internal static bool IsParameterConverter(EntityColumnInfo columnInfo) + { + return columnInfo != null && columnInfo.SqlParameterDbType != null && columnInfo.SqlParameterDbType is Type + && typeof(ISugarDataConverter).IsAssignableFrom(columnInfo.SqlParameterDbType as Type); + } + internal static SugarParameter GetParameterConverter(int index, ISqlSugarClient db, object value, Expression oppoSiteExpression, EntityColumnInfo columnInfo) + { + var entity = db.EntityMaintenance.GetEntityInfo(oppoSiteExpression.Type); + var type = columnInfo.SqlParameterDbType as Type; + var ParameterConverter = type.GetMethod("ParameterConverter").MakeGenericMethod(columnInfo.PropertyInfo.PropertyType); + var obj = Activator.CreateInstance(type); + var p = ParameterConverter.Invoke(obj, new object[] { value, 100 + index }) as SugarParameter; + return p; + } + internal static SugarParameter GetParameterConverter(int index, ISqlSugarClient db, object value, EntityInfo entity, EntityColumnInfo columnInfo) + { + var type = columnInfo.SqlParameterDbType as Type; + var ParameterConverter = type.GetMethod("ParameterConverter").MakeGenericMethod(columnInfo.PropertyInfo.PropertyType); + var obj = Activator.CreateInstance(type); + var p = ParameterConverter.Invoke(obj, new object[] { value, 100 + index }) as SugarParameter; + return p; + } + internal static object QueryConverter(int index, ISqlSugarClient db, IDataReader dataReader, EntityInfo entity, EntityColumnInfo columnInfo) + { + var type = columnInfo.SqlParameterDbType as Type; + var ParameterConverter = type.GetMethod("QueryConverter").MakeGenericMethod(columnInfo.PropertyInfo.PropertyType); + var obj = Activator.CreateInstance(type); + var p = ParameterConverter.Invoke(obj, new object[] { dataReader, index }); + return p; + } + internal static bool IsErrorParameterName(ConnectionConfig connectionConfig, DbColumnInfo columnInfo) + { + return connectionConfig.MoreSettings?.IsCorrectErrorSqlParameterName == true && + columnInfo.DbColumnName.IsContainsIn("-", " ", ".", "(", ")", "(", ")"); + } + + public static bool StringCheckFirstAndLast(string withString, string first, string last) + { + return withString.StartsWith(first) && withString.EndsWith(last); + } + public static bool HasInterface(Type targetType, Type interfaceType) + { + if (targetType == null || interfaceType == null || !interfaceType.IsInterface) + { + return false; + } + + return interfaceType.IsAssignableFrom(targetType); + } + public static void ClearPublicProperties(T obj, EntityInfo entity) + { + if (obj == null) + { + throw new ArgumentNullException(nameof(obj)); + } + + Type type = typeof(T); + + foreach (var column in entity.Columns) + { + if (column.PropertyInfo.CanWrite && column.PropertyInfo.GetSetMethod() != null) + { + Type propertyType = column.PropertyInfo.PropertyType; + object defaultValue = propertyType.IsValueType ? Activator.CreateInstance(propertyType) : null; + column.PropertyInfo.SetValue(obj, defaultValue); + } + } + } + + internal static Expression GetIncludeExpression(string navMemberName, EntityInfo entityInfo, out Type properyItemType, out bool isList) + { + var navInfo = entityInfo.Columns.Where(it => it.Navigat != null && it.PropertyName.EqualCase(navMemberName)).FirstOrDefault(); + var properyType = navInfo.PropertyInfo.PropertyType; + properyItemType = properyType; + if (properyType.FullName.IsCollectionsList()) + { + properyItemType = properyType.GetGenericArguments()[0]; + isList = true; + } + else + { + isList = false; + } + return ExpressionBuilderHelper.CreateExpressionSelectField(entityInfo.Type, navInfo.PropertyName, properyType); + } + public static string RemoveEqualOne(string value) + { + value = value.TrimEnd(' ').TrimEnd('1').TrimEnd('='); + return value; + } + /// + /// Available only in Select,Handles logic that cannot be completed by an expression + /// + /// + /// + /// + internal static object GetFormatValue(object addValue, QueryableFormat valueFomatInfo) + { + if (valueFomatInfo.MethodName == "ToString") + { + if (valueFomatInfo.Type == UtilConstants.GuidType) + { + addValue = Guid.Parse(addValue + "").ToString(valueFomatInfo.Format); + } + else if (valueFomatInfo.Type == UtilConstants.ByteType) + { + addValue = Convert.ToByte(addValue + "").ToString(valueFomatInfo.Format); + } + else if (valueFomatInfo.Type == UtilConstants.IntType) + { + addValue = Convert.ToInt32(addValue + "").ToString(valueFomatInfo.Format); + } + else if (valueFomatInfo.Type == UtilConstants.LongType) + { + addValue = Convert.ToInt64(addValue + "").ToString(valueFomatInfo.Format); + } + else if (valueFomatInfo.Type == UtilConstants.UIntType) + { + addValue = Convert.ToUInt32(addValue + "").ToString(valueFomatInfo.Format); + } + else if (valueFomatInfo.Type == UtilConstants.ULongType) + { + addValue = Convert.ToUInt64(addValue + "").ToString(valueFomatInfo.Format); + } + else if (valueFomatInfo.Type == UtilConstants.DecType) + { + addValue = Convert.ToDecimal(addValue + "").ToString(valueFomatInfo.Format); + } + else if (valueFomatInfo.Type == UtilConstants.DobType) + { + addValue = Convert.ToDouble(addValue + "").ToString(valueFomatInfo.Format); + } + else if (valueFomatInfo.TypeString == "Enum") + { + addValue = ChangeType2(addValue, valueFomatInfo.Type)?.ToString(); + } + } + else if (valueFomatInfo.MethodName == "OnlyInSelectConvertToString") + { + + var methodInfo = valueFomatInfo.MethodInfo; + if (methodInfo != null) + { + // 如果方法是静态的,传递null作为第一个参数,否则传递类的实例 + object instance = methodInfo.IsStatic ? null : Activator.CreateInstance(methodInfo.ReflectedType); + + // 创建一个包含参数值的object数组 + object[] parameters = new object[] { addValue }; + + // 调用方法 + addValue = methodInfo.Invoke(instance, parameters); + } + } + return addValue; + } + public static int CountSubstringOccurrences(string mainString, string searchString) + { + string[] substrings = mainString.Split(new string[] { searchString }, StringSplitOptions.None); + return substrings.Length - 1; + } + public static string RemoveBeforeFirstWhere(string query) + { + int whereIndex = query.IndexOf("WHERE", StringComparison.OrdinalIgnoreCase); + if (whereIndex >= 0) + { + return query.Substring(whereIndex + "WHERE".Length); + } + else + { + return query; + } + } + public static List ConvertToListOfObjects(object inValues) + { + // 创建一个新的List并逐个将元素转换并添加到其中 + List resultList = new List(); + foreach (var item in (IEnumerable)inValues) + { + resultList.Add(item); + } + + return resultList; + } + public static bool IsValueTypeArray(object memberValue) + { + return memberValue is List || + memberValue is string[] || + memberValue is List || + memberValue is int[] || + memberValue is List || + memberValue is Guid[] || + memberValue is List || + memberValue is long[] || + memberValue is List || + memberValue is int?[] || + memberValue is List || + memberValue is Guid?[] || + memberValue is List || + memberValue is long?[] || + memberValue is List || + memberValue is float[] || + memberValue is List || + memberValue is double[] || + memberValue is List || + memberValue is decimal[] || + memberValue is List || + memberValue is DateTime[] || + memberValue is List || + memberValue is TimeSpan[] || + memberValue is List || + memberValue is bool[] || + memberValue is List || + memberValue is byte[] || + memberValue is List || + memberValue is char[] || + memberValue is List || + memberValue is short[] || + memberValue is List || + memberValue is ushort[] || + memberValue is List || + memberValue is uint[] || + memberValue is List || + memberValue is ulong[] || + memberValue is List || + memberValue is sbyte[] || + memberValue is List || + memberValue is object[] || + memberValue is List || + memberValue is int?[] || + memberValue is List || + memberValue is Guid?[] || + memberValue is List || + memberValue is long?[]; + } + internal static void EndCustomSplitTable(ISqlSugarClient context, Type entityType) + { + if (context == null || entityType == null) + { + return; + } + var splitTableAttribute = entityType.GetCustomAttribute(); + if (splitTableAttribute == null) + { + return; + } + if (splitTableAttribute.CustomSplitTableService != null) + { + context.CurrentConnectionConfig.ConfigureExternalServices.SplitTableService = null; + } + } + + internal static void StartCustomSplitTable(ISqlSugarClient context, Type entityType) + { + if (context == null || entityType == null) + { + return; + } + var splitTableAttribute = entityType.GetCustomAttribute(); + if (splitTableAttribute == null) + { + return; + } + if (splitTableAttribute.CustomSplitTableService != null) + { + context.CurrentConnectionConfig.ConfigureExternalServices.SplitTableService + = (ISplitTableService)Activator.CreateInstance(splitTableAttribute.CustomSplitTableService); + } + if ( + context?.CurrentConnectionConfig?.ConfigureExternalServices?.SplitTableService != null + && splitTableAttribute.CustomSplitTableService == null + && context.EntityMaintenance.GetEntityInfo(entityType).DbTableName?.EndsWith("_{year}{month}{day}") == true + && !context.EntityMaintenance.GetEntityInfo(entityType).DbTableName?.Replace("_{year}{month}{day}", "")?.Contains("{") == true + ) + { + context.CurrentConnectionConfig.ConfigureExternalServices.SplitTableService + = null; + } + } + public static void ConvertParameter(SugarParameter p, ISqlBuilder builder) + { + if (!p.ParameterName.StartsWith(builder.SqlParameterKeyWord)) + { + p.ParameterName = (builder.SqlParameterKeyWord + p.ParameterName.TrimStart('@')); + } + } + public static object SetAnonymousObjectPropertyValue(object obj, string propertyName, object propertyValue) + { + if (obj.GetType().IsAnonymousType()) // 判断是否为匿名对象 + { + var objType = obj.GetType(); + var objFields = objType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic); + foreach (var field in objFields) // 遍历字段列表,查找需要修改的属性 + { + if (field.Name == $"<{propertyName}>i__Field") + { + field.SetValue(obj, propertyValue); // 使用反射修改属性值 + break; + } + } + } + else + { + obj.GetType().GetProperty(propertyName).SetValue(obj, propertyValue); + } + return obj; + } + + internal static bool IsNumberArray(Type type) + { + + return type.IsIn(typeof(int[]), + typeof(long[]), + typeof(short[]), + typeof(uint[]), + typeof(ulong[]), + typeof(ushort[]), + typeof(int?[]), + typeof(long?[]), + typeof(short?[]), + typeof(uint?[]), + typeof(ulong?[]), + typeof(ushort?[]), + typeof(List), + typeof(List), + typeof(List), + typeof(List), + typeof(List), + typeof(List), + typeof(List), + typeof(List), + typeof(List), + typeof(List), + typeof(List), + typeof(List)); + } + public static string GetNativeSql(string sql, SugarParameter[] pars) + { + if (pars == null || pars.Length == 0) + return "\r\n[Sql]:" + sql + "\r\n"; + return $"\r\n[Sql]:{sql} \r\n[Pars]:{string.Join(" ", pars.Select(it => $"\r\n[Name]:{it.ParameterName} [Value]:{it.Value} [Type]:{it.DbType} {(it.IsNvarchar2 ? "nvarchar2" : "")} "))} \r\n"; + } + public static string ToUnderLine(string str, bool isToUpper = false) + { + if (str == null || str.Contains("_")) + { + return str; + } + else if (isToUpper) + { + return string.Concat(str.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString())).ToUpper(); + } + else + { + return string.Concat(str.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString())).ToLower(); + } + } + internal static bool IsArrayMember(Expression expression, SqlSugarProvider context) + { + if (expression == null) + return false; + if (!(expression is LambdaExpression)) + return false; + var lambda = (LambdaExpression)expression; + if (!(lambda.Body is MemberExpression)) + return false; + var member = lambda.Body as MemberExpression; + if (!(member.Type.IsClass())) + return false; + if (member.Expression == null) + return false; + var entity = context.EntityMaintenance.GetEntityInfo(member.Expression.Type); + var json = entity.Columns.FirstOrDefault(z => z.IsArray && z.PropertyName == member.Member.Name); + return json != null; + } + internal static bool IsJsonMember(Expression expression, SqlSugarProvider context) + { + if (expression == null) + return false; + if (!(expression is LambdaExpression)) + return false; + var lambda = (LambdaExpression)expression; + if (!(lambda.Body is MemberExpression)) + return false; + var member = lambda.Body as MemberExpression; + if (!(member.Type.IsClass())) + return false; + if (member.Expression == null) + return false; + var entity = context.EntityMaintenance.GetEntityInfo(member.Expression.Type); + var json = entity.Columns.FirstOrDefault(z => z.IsJson && z.PropertyName == member.Member.Name); + return json != null; + } + public static string GetSeparatorChar() + { + return Path.Combine("a", "a").Replace("a", ""); + } + public static bool IsParentheses(object name) + { + return name.ObjToString().Trim().Last() == ')' && name.ObjToString().Trim().First() == '('; + } + + internal static bool IsDefaultValue(object value) + { + if (value == null) return true; + return value.Equals(UtilMethods.GetDefaultValue(value.GetType())); + } + + internal static DateTime ConvertFromDateTimeOffset(DateTimeOffset dateTime) + { + if (dateTime.Offset.Equals(TimeSpan.Zero)) + return dateTime.UtcDateTime; + else if (dateTime.Offset.Equals(TimeZoneInfo.Local.GetUtcOffset(dateTime.DateTime))) + return DateTime.SpecifyKind(dateTime.DateTime, DateTimeKind.Local); + else + return dateTime.DateTime; + } + + internal static object To(object value, Type destinationType) + { + return To(value, destinationType, CultureInfo.InvariantCulture); + } + + internal static object To(object value, Type destinationType, CultureInfo culture) + { + if (value != null) + { + destinationType = UtilMethods.GetUnderType(destinationType); + var sourceType = value.GetType(); + if (destinationType.Name == "DateOnly" && sourceType == typeof(string)) + { + var type = Type.GetType("System.DateOnly", true, true); + var method = type.GetMethods().FirstOrDefault(it => it.GetParameters().Length == 1 && it.Name == "FromDateTime"); + return method.Invoke(null, new object[] { Convert.ToDateTime(value) }); + } + else if (destinationType.FullName == "System.Ulid") + { + var method = destinationType.GetMyMethod("Parse", 1); + if (method != null) + { + var result = method.Invoke(null, new object[] { value }); + return result; + } + } + else if (value is byte[] bytes && bytes.Length == 1 && destinationType == typeof(char)) + { + return (char)(bytes)[0]; + } + else if (value is DateTime && destinationType == typeof(TimeSpan)) + { + value = Convert.ToDateTime(value).TimeOfDay; + } + else if (value is DateTime && destinationType.FullName == "System.TimeOnly") + { + value = Convert.ToDateTime(value).TimeOfDay; + } + var destinationConverter = TypeDescriptor.GetConverter(destinationType); + if (destinationConverter != null && destinationConverter.CanConvertFrom(value.GetType())) + return destinationConverter.ConvertFrom(null, culture, value); + + var sourceConverter = TypeDescriptor.GetConverter(sourceType); + if (sourceConverter != null && sourceConverter.CanConvertTo(destinationType)) + return sourceConverter.ConvertTo(null, culture, value, destinationType); + + if (destinationType.IsEnum && value is int) + return Enum.ToObject(destinationType, (int)value); + + if (destinationType.Name == "TimeOnly" && sourceType.Name != "TimeOnly") + { + var type = Type.GetType("System.TimeOnly", true, true); + var method = type.GetMethods().FirstOrDefault(it => it.GetParameters().Length == 1 && it.Name == "FromTimeSpan"); + return method.Invoke(null, new object[] { value }); + } + if (destinationType.Name == "DateOnly" && sourceType.Name != "DateOnly") + { + var type = Type.GetType("System.DateOnly", true, true); + var method = type.GetMethods().FirstOrDefault(it => it.GetParameters().Length == 1 && it.Name == "FromDateTime"); + return method.Invoke(null, new object[] { value }); + } + + if (!destinationType.IsInstanceOfType(value)) + return Convert.ChangeType(value, destinationType, culture); + } + return value; + } + public static bool IsAnyAsyncMethod(StackFrame[] methods) + { + bool isAsync = false; + foreach (var item in methods) + { + if (UtilMethods.IsAsyncMethod(item.GetMethod())) + { + isAsync = true; + break; + } + } + return isAsync; + } + + + public static ConnectionConfig CopyConfig(ConnectionConfig it) + { + return new ConnectionConfig() + { + AopEvents = it.AopEvents == null ? null : new AopEvents() + { + DataExecuting = it.AopEvents?.DataExecuting, + OnDiffLogEvent = it.AopEvents?.OnDiffLogEvent, + OnError = it.AopEvents?.OnError, + OnExecutingChangeSql = it.AopEvents?.OnExecutingChangeSql, + OnLogExecuted = it.AopEvents?.OnLogExecuted, + OnLogExecuting = it.AopEvents?.OnLogExecuting, + DataExecuted = it.AopEvents?.DataExecuted, + CheckConnectionExecuted = it.AopEvents?.CheckConnectionExecuted, + CheckConnectionExecuting = it.AopEvents?.CheckConnectionExecuting, + OnGetDataReadered = it.AopEvents?.OnGetDataReadered, + OnGetDataReadering = it.AopEvents?.OnGetDataReadering, + }, + ConfigId = it.ConfigId, + ConfigureExternalServices = it.ConfigureExternalServices == null ? null : new ConfigureExternalServices() + { + AppendDataReaderTypeMappings = it.ConfigureExternalServices.AppendDataReaderTypeMappings, + DataInfoCacheService = it.ConfigureExternalServices.DataInfoCacheService, + EntityNameService = it.ConfigureExternalServices.EntityNameService, + EntityService = it.ConfigureExternalServices.EntityService, + RazorService = it.ConfigureExternalServices.RazorService, + ReflectionInoCacheService = it.ConfigureExternalServices.ReflectionInoCacheService, + SerializeService = it.ConfigureExternalServices.SerializeService, + SplitTableService = it.ConfigureExternalServices.SplitTableService, + SqlFuncServices = it.ConfigureExternalServices.SqlFuncServices + }, + ConnectionString = it.ConnectionString, + DbType = it.DbType, + DbLinkName = it.DbLinkName, + IndexSuffix = it.IndexSuffix, + InitKeyType = it.InitKeyType, + IsAutoCloseConnection = it.IsAutoCloseConnection, + LanguageType = it.LanguageType, + MoreSettings = it.MoreSettings == null ? null : new ConnMoreSettings() + { + DefaultCacheDurationInSeconds = it.MoreSettings.DefaultCacheDurationInSeconds, + DisableNvarchar = it.MoreSettings.DisableNvarchar, + PgSqlIsAutoToLower = it.MoreSettings.PgSqlIsAutoToLower, + PgSqlIsAutoToLowerCodeFirst = it.MoreSettings.PgSqlIsAutoToLowerCodeFirst, + IsAutoRemoveDataCache = it.MoreSettings.IsAutoRemoveDataCache, + IsWithNoLockQuery = it.MoreSettings.IsWithNoLockQuery, + DisableWithNoLockWithTran = it.MoreSettings.DisableWithNoLockWithTran, + TableEnumIsString = it.MoreSettings.TableEnumIsString, + DisableMillisecond = it.MoreSettings.DisableMillisecond, + DbMinDate = it.MoreSettings.DbMinDate, + IsNoReadXmlDescription = it.MoreSettings.IsNoReadXmlDescription, + SqlServerCodeFirstNvarchar = it.MoreSettings.SqlServerCodeFirstNvarchar, + OracleCodeFirstNvarchar2 = it.MoreSettings.OracleCodeFirstNvarchar2, + IsAutoToUpper = it.MoreSettings.IsAutoToUpper, + IsAutoDeleteQueryFilter = it.MoreSettings.IsAutoDeleteQueryFilter, + IsAutoUpdateQueryFilter = it.MoreSettings.IsAutoUpdateQueryFilter, + EnableModelFuncMappingColumn = it.MoreSettings.EnableModelFuncMappingColumn, + EnableOracleIdentity = it.MoreSettings.EnableOracleIdentity, + IsWithNoLockSubquery = it.MoreSettings.IsWithNoLockSubquery, + EnableCodeFirstUpdatePrecision = it.MoreSettings.EnableCodeFirstUpdatePrecision, + SqliteCodeFirstEnableDefaultValue = it.MoreSettings.SqliteCodeFirstEnableDefaultValue, + SqliteCodeFirstEnableDescription = it.MoreSettings.SqliteCodeFirstEnableDescription, + IsCorrectErrorSqlParameterName = it.MoreSettings.IsCorrectErrorSqlParameterName, + SqliteCodeFirstEnableDropColumn = it.MoreSettings.SqliteCodeFirstEnableDropColumn, + MaxParameterNameLength = it.MoreSettings.MaxParameterNameLength, + DisableQueryWhereColumnRemoveTrim = it.MoreSettings.DisableQueryWhereColumnRemoveTrim, + DatabaseModel = it.MoreSettings.DatabaseModel, + EnableILike = it.MoreSettings.EnableILike, + ClickHouseEnableFinal = it.MoreSettings.ClickHouseEnableFinal, + PgSqlIsAutoToLowerSchema = it.MoreSettings.PgSqlIsAutoToLowerSchema + + }, + SqlMiddle = it.SqlMiddle == null ? null : new SqlMiddle + { + IsSqlMiddle = it.SqlMiddle.IsSqlMiddle, + ExecuteCommand = it.SqlMiddle.ExecuteCommand, + ExecuteCommandAsync = it.SqlMiddle.ExecuteCommandAsync, + GetDataReader = it.SqlMiddle.GetDataReader, + GetDataReaderAsync = it.SqlMiddle.GetDataReaderAsync, + GetDataSetAll = it.SqlMiddle.GetDataSetAll, + GetDataSetAllAsync = it.SqlMiddle.GetDataSetAllAsync, + GetScalar = it.SqlMiddle.GetScalar, + GetScalarAsync = it.SqlMiddle.GetScalarAsync + }, + SlaveConnectionConfigs = it.SlaveConnectionConfigs + }; + } + + internal static object GetRandomByType(Type underType) + { + if (underType == UtilConstants.GuidType) + { + return Guid.NewGuid(); + } + else if (underType == UtilConstants.LongType) + { + return SnowFlakeSingle.Instance.NextId(); + } + else if (underType == UtilConstants.StringType) + { + return Guid.NewGuid() + ""; + } + else if (underType == UtilConstants.DateType) + { + return System.DateTime.Now; + } + else + { + return Guid.NewGuid() + ""; + } + } + + public static bool IsAsyncMethod(MethodBase method) + { + if (method == null) + { + return false; + } + if (method.DeclaringType != null) + { + if (method.DeclaringType.GetInterfaces().Contains(typeof(IAsyncStateMachine))) + { + return true; + } + } + var name = method.Name; + if (name.Contains("OutputAsyncCausalityEvents")) + { + return true; + } + if (name.Contains("OutputWaitEtwEvents")) + { + return true; + } + if (name.Contains("ExecuteAsync")) + { + return true; + } + //if (method?.DeclaringType?.FullName?.Contains("Furion.InternalApp")==true) + //{ + // return false; + //} + Type attType = typeof(AsyncStateMachineAttribute); + var attrib = (AsyncStateMachineAttribute)method.GetCustomAttribute(attType); + return (attrib != null); + } + + public static StackTraceInfo GetStackTrace() + { + + StackTrace st = new StackTrace(true); + StackTraceInfo info = new StackTraceInfo(); + info.MyStackTraceList = new List(); + info.SugarStackTraceList = new List(); + for (int i = 0; i < st.FrameCount; i++) + { + var frame = st.GetFrame(i); + if (frame.GetMethod().Module.Name.ToLower() != "sqlsugar.dll" && frame.GetMethod().Name.First() != '<') + { + info.MyStackTraceList.Add(new StackTraceInfoItem() + { + FileName = frame.GetFileName(), + MethodName = frame.GetMethod().Name, + Line = frame.GetFileLineNumber() + }); + } + else + { + info.SugarStackTraceList.Add(new StackTraceInfoItem() + { + FileName = frame.GetFileName(), + MethodName = frame.GetMethod().Name, + Line = frame.GetFileLineNumber() + }); + } + } + return info; + } + + internal static object GetConvertValue(object entityValue) + { + if (entityValue != null && entityValue is DateTime) + { + entityValue = entityValue.ObjToDate().ToString("yyyy-MM-dd HH:mm:ss.fff"); + } + return entityValue; + } + + internal static T To(object value) + { + return (T)To(value, typeof(T)); + } + + internal static DateTime GetMinDate(ConnectionConfig currentConnectionConfig) + { + if (currentConnectionConfig.MoreSettings == null) + { + return Convert.ToDateTime("1900-01-01"); + } + else if (currentConnectionConfig.MoreSettings.DbMinDate == null) + { + return Convert.ToDateTime("1900-01-01"); + } + else + { + return currentConnectionConfig.MoreSettings.DbMinDate.Value; + } + } + + public static Type GetUnderType(Type oldType) + { + Type type = Nullable.GetUnderlyingType(oldType); + return type == null ? oldType : type; + } + public static object GetDefaultValue(Type type) + { + return type.IsValueType ? Activator.CreateInstance(type) : null; + } + public static string ReplaceFirstMatch(string input, string pattern, string replacement) + { + Regex regex = new Regex(pattern); + return regex.Replace(input, replacement, 1); + } + public static string ReplaceSqlParameter(string itemSql, SugarParameter itemParameter, string newName) + { + itemSql = Regex.Replace(itemSql, string.Format(@"{0} ", "\\" + itemParameter.ParameterName), newName + " ", RegexOptions.IgnoreCase); + itemSql = Regex.Replace(itemSql, string.Format(@"{0}\)", "\\" + itemParameter.ParameterName), newName + ")", RegexOptions.IgnoreCase); + itemSql = Regex.Replace(itemSql, string.Format(@"{0}\,", "\\" + itemParameter.ParameterName), newName + ",", RegexOptions.IgnoreCase); + itemSql = Regex.Replace(itemSql, string.Format(@"{0}$", "\\" + itemParameter.ParameterName), newName, RegexOptions.IgnoreCase); + itemSql = Regex.Replace(itemSql, string.Format(@"\+{0}\+", "\\" + itemParameter.ParameterName), "+" + newName + "+", RegexOptions.IgnoreCase); + itemSql = Regex.Replace(itemSql, string.Format(@"\+{0} ", "\\" + itemParameter.ParameterName), "+" + newName + " ", RegexOptions.IgnoreCase); + itemSql = Regex.Replace(itemSql, string.Format(@" {0}\+", "\\" + itemParameter.ParameterName), " " + newName + "+", RegexOptions.IgnoreCase); + itemSql = Regex.Replace(itemSql, string.Format(@"\|\|{0}\|\|", "\\" + itemParameter.ParameterName), "||" + newName + "||", RegexOptions.IgnoreCase); + itemSql = Regex.Replace(itemSql, string.Format(@"\={0}\+", "\\" + itemParameter.ParameterName), "=" + newName + "+", RegexOptions.IgnoreCase); + itemSql = Regex.Replace(itemSql, string.Format(@"{0}\|\|", "\\" + itemParameter.ParameterName), newName + "||", RegexOptions.IgnoreCase); + return itemSql; + } + internal static Type GetRootBaseType(Type entityType) + { + var baseType = entityType.BaseType; + while (baseType != null && baseType.BaseType != UtilConstants.ObjType) + { + baseType = baseType.BaseType; + } + return baseType; + } + + + internal static Type GetUnderType(PropertyInfo propertyInfo, ref bool isNullable) + { + Type unType = Nullable.GetUnderlyingType(propertyInfo.PropertyType); + isNullable = unType != null; + unType = unType ?? propertyInfo.PropertyType; + return unType; + } + + internal static Type GetUnderType(PropertyInfo propertyInfo) + { + Type unType = Nullable.GetUnderlyingType(propertyInfo.PropertyType); + unType = unType ?? propertyInfo.PropertyType; + return unType; + } + + internal static bool IsNullable(PropertyInfo propertyInfo) + { + Type unType = Nullable.GetUnderlyingType(propertyInfo.PropertyType); + return unType != null; + } + + internal static bool IsNullable(Type type) + { + Type unType = Nullable.GetUnderlyingType(type); + return unType != null; + } + internal static T IsNullReturnNew(T returnObj) where T : new() + { + if (returnObj.IsNullOrEmpty()) + { + returnObj = new T(); + } + return returnObj; + } + public static object ChangeType2(object value, Type type) + { + if (value is byte[] && type == UtilConstants.StringType) + { + return Encoding.UTF8.GetString(value as byte[]); + } + if (value == null && type.IsGenericType) return Activator.CreateInstance(type); + if (value == null) return null; + if (type == value.GetType()) return value; + if (type.IsEnum) + { + if (value is string) + return Enum.Parse(type, value as string); + else + return Enum.ToObject(type, value); + } + if (value is string && type == typeof(Guid?)) return value.IsNullOrEmpty() ? null : (Guid?)new Guid(value as string); + if (!type.IsInterface && type.IsGenericType) + { + Type innerType = type.GetGenericArguments()[0]; + object innerValue = ChangeType(value, innerType); + return Activator.CreateInstance(type, new object[] { innerValue }); + } + if (value is string && type == typeof(Guid)) return new Guid(value as string); + if (value is string && type == typeof(Version)) return new Version(value as string); + if (!(value is IConvertible)) return value; + if (value is DateTime && type.FullName == "System.DateOnly") + { + value = UtilMethods.DateTimeToDateOnly(value); + } + return Convert.ChangeType(value, type); + } + + internal static T ChangeType(T obj, Type type) + { + return (T)Convert.ChangeType(obj, type); + } + + internal static T ChangeType(T obj) + { + return (T)Convert.ChangeType(obj, typeof(T)); + } + + internal static DateTimeOffset GetDateTimeOffsetByDateTime(DateTime date) + { + date = DateTime.SpecifyKind(date, DateTimeKind.Utc); + DateTimeOffset utcTime2 = date; + return utcTime2; + } + + internal static void RepairReplicationParameters(ref string appendSql, SugarParameter[] parameters, int addIndex, string append = null) + { + if (appendSql.HasValue() && parameters.HasValue()) + { + foreach (var parameter in parameters.OrderByDescending(it => it.ParameterName.Length)) + { + //Compatible with.NET CORE parameters case + var name = parameter.ParameterName; + string newName = name + append + addIndex; + appendSql = ReplaceSqlParameter(appendSql, parameter, newName); + parameter.ParameterName = newName; + } + } + } + internal static void RepairReplicationParameters(ISqlSugarClient db, ref string appendSql, SugarParameter[] parameters, int addIndex, string append = null) + { + if (appendSql.HasValue() && parameters.HasValue()) + { + foreach (var parameter in parameters.OrderByDescending(it => it.ParameterName.Length)) + { + //Compatible with.NET CORE parameters case + var name = parameter.ParameterName; + string newName = name + append + addIndex; + var maxLength = db.CurrentConnectionConfig.MoreSettings.MaxParameterNameLength; + if (newName.Length > maxLength) + { + newName = (name.Substring(0, 1) + name.GetNonNegativeHashCodeString() + "_" + addIndex); + } + appendSql = ReplaceSqlParameter(appendSql, parameter, newName); + parameter.ParameterName = newName; + } + } + } + + internal static string GetPackTable(string sql, string shortName) + { + return string.Format(" ({0}) {1} ", sql, shortName); + } + + public static Func GetTypeConvert(object value) + { + if (value is int || value is uint || value is int? || value is uint?) + { + return x => Convert.ToInt32(x); + } + else if (value is short || value is ushort || value is short? || value is ushort?) + { + return x => Convert.ToInt16(x); + } + else if (value is long || value is long? || value is ulong? || value is long?) + { + return x => Convert.ToInt64(x); + } + else if (value is DateTime || value is DateTime?) + { + return x => Convert.ToDateTime(x); + } + else if (value is bool || value is bool?) + { + return x => Convert.ToBoolean(x); + } + return null; + } + + internal static string GetTypeName(object value) + { + if (value == null) + { + return null; + } + else + { + return value.GetType().Name; + } + } + + internal static string GetParenthesesValue(string dbTypeName) + { + if (Regex.IsMatch(dbTypeName, @"\(.+\)")) + { + if (Regex.IsMatch(dbTypeName, @"SimpleAggregateFunction")) + dbTypeName = Regex.Match(dbTypeName, @"((?<=,\s)[^Nullable]\w+)|((?<=Nullable\()\w+)").Value; + else + dbTypeName = Regex.Replace(dbTypeName, @"\(.+\)", ""); + } + dbTypeName = dbTypeName.Trim(); + return dbTypeName; + } + + internal static T GetOldValue(T value, Action action) + { + action(); + return value; + } + + internal static object DefaultForType(Type targetType) + { + return targetType.IsValueType ? Activator.CreateInstance(targetType) : null; + } + + internal static Int64 GetLong(byte[] bytes) + { + return Convert.ToInt64(string.Join("", bytes).PadRight(20, '0')); + } + public static object GetPropertyValue(T t, string PropertyName) + { + return t.GetType().GetProperty(PropertyName).GetValue(t, null); + } + internal static string GetMD5(string myString) + { + MD5 md5 = new MD5CryptoServiceProvider(); + byte[] fromData = System.Text.Encoding.Unicode.GetBytes(myString); + byte[] targetData = md5.ComputeHash(fromData); + string byte2String = null; + + for (int i = 0; i < targetData.Length; i++) + { + byte2String += targetData[i].ToString("x"); + } + + return byte2String; + } + + public static string EncodeBase64(string code) + { + if (StaticConfig.Encode != null) + { + return StaticConfig.Encode(code); + } + if (code.IsNullOrEmpty()) return code; + string encode = ""; + byte[] bytes = Encoding.GetEncoding("utf-8").GetBytes(code); + try + { + encode = Convert.ToBase64String(bytes); + } + catch + { + encode = code; + } + return encode; + } + public static string ConvertNumbersToString(string value) + { + string[] splitInt = value.Split(new char[] { '9' }, StringSplitOptions.RemoveEmptyEntries); + + var splitChars = splitInt.Select(s => Convert.ToChar( + Convert.ToInt32(s, 8) + ).ToString()); + + return string.Join("", splitChars); + } + public static string ConvertStringToNumbers(string value) + { + StringBuilder sb = new StringBuilder(); + + foreach (char c in value) + { + int cAscil = (int)c; + sb.Append(Convert.ToString(c, 8) + "9"); + } + + return sb.ToString(); + } + + public static string DecodeBase64(string code) + { + try + { + if (StaticConfig.Decode != null) + { + return StaticConfig.Decode(code); + } + if (code.IsNullOrEmpty()) return code; + string decode = ""; + byte[] bytes = Convert.FromBase64String(code); + try + { + decode = Encoding.GetEncoding("utf-8").GetString(bytes); + } + catch + { + decode = code; + } + return decode; + } + catch + { + return code; + } + } + + public static string GetSqlValue(object value) + { + if (value == null) + { + return "null"; + } + else if (UtilMethods.IsNumber(value.GetType().Name)) + { + return value.ObjToString(); + } + else if (value is DateTime) + { + return UtilMethods.GetConvertValue(value) + ""; + } + else + { + return value.ToSqlValue(); + } + } + + public static void DataInoveByExpresson(Type[] datas, MethodCallExpression callExpresion) + { + var methodInfo = callExpresion.Method; + foreach (var item in datas) + { + if (item != null) + { + if (callExpresion.Arguments.Count == 0) + { + methodInfo.Invoke(item, null); + } + else + { + List methodParameters = new List(); + foreach (var callItem in callExpresion.Arguments) + { + var parameter = callItem.GetType().GetProperties().FirstOrDefault(it => it.Name == "Value"); + if (parameter == null) + { + var value = LambdaExpression.Lambda(callItem).Compile().DynamicInvoke(); + methodParameters.Add(value); + } + else + { + var value = parameter.GetValue(callItem, null); + methodParameters.Add(value); + } + } + methodInfo.Invoke(item, methodParameters.ToArray()); + } + } + } + } + + public static Dictionary EnumToDictionary() + { + Dictionary dic = new Dictionary(); + if (!typeof(T).IsEnum) + { + return dic; + } + string desc = string.Empty; + foreach (var item in Enum.GetValues(typeof(T))) + { + var key = item.ToString().ToLower(); + if (!dic.ContainsKey(key)) + dic.Add(key, (T)item); + } + return dic; + } + + public static Type GetTypeByTypeName(string ctypename) + { + + if (ctypename.EqualCase(UtilConstants.DecType.Name)) + { + return UtilConstants.DecType; + } + else if (ctypename.EqualCase(UtilConstants.DobType.Name)) + { + return UtilConstants.DobType; + } + else if (ctypename.EqualCase(UtilConstants.DateType.Name)) + { + return UtilConstants.DateType; + } + else if (ctypename.EqualCase(UtilConstants.IntType.Name)) + { + return UtilConstants.IntType; + } + else if (ctypename.EqualCase(UtilConstants.BoolType.Name)) + { + return UtilConstants.BoolType; + } + else if (ctypename.EqualCase(UtilConstants.LongType.Name)) + { + return UtilConstants.LongType; + } + else if (ctypename.EqualCase(UtilConstants.ShortType.Name)) + { + return UtilConstants.ShortType; + } + else if (ctypename.EqualCase(UtilConstants.DateTimeOffsetType.Name)) + { + return UtilConstants.DateTimeOffsetType; + } + else if (ctypename.EqualCase(UtilConstants.GuidType.Name)) + { + return UtilConstants.GuidType; + } + else if (ctypename.EqualCase("int")) + { + return UtilConstants.IntType; + } + else if (ctypename.EqualCase("long")) + { + return UtilConstants.LongType; + } + else if (ctypename.EqualCase("short")) + { + return UtilConstants.ShortType; + } + else if (ctypename.EqualCase("byte")) + { + return UtilConstants.ByteType; + } + else if (ctypename.EqualCase("uint")) + { + return UtilConstants.UIntType; + } + else if (ctypename.EqualCase("ulong")) + { + return UtilConstants.ULongType; + } + else if (ctypename.EqualCase("ushort")) + { + return UtilConstants.UShortType; + } + else if (ctypename.EqualCase("uint32")) + { + return UtilConstants.UIntType; + } + else if (ctypename.EqualCase("uint64")) + { + return UtilConstants.ULongType; + } + else if (ctypename.EqualCase("bool")) + { + return UtilConstants.BoolType; + } + else if (ctypename.EqualCase("ToBoolean")) + { + return UtilConstants.BoolType; + } + else if (ctypename.EqualCase("uint16")) + { + return UtilConstants.UShortType; + } + else if (ctypename.EqualCase(UtilConstants.ByteArrayType.Name)) + { + return UtilConstants.ByteArrayType; + } + else + { + return UtilConstants.StringType; + } + } + public static object ConvertDataByTypeName(string ctypename, string value) + { + var item = new ConditionalModel() + { + CSharpTypeName = ctypename, + FieldValue = value + }; + if (item.FieldValue == string.Empty && item.CSharpTypeName.HasValue() && !item.CSharpTypeName.EqualCase("string")) + { + return null; + } + if (item.CSharpTypeName.EqualCase(UtilConstants.DecType.Name)) + { + return Convert.ToDecimal(item.FieldValue); + } + else if (item.CSharpTypeName.EqualCase(UtilConstants.DobType.Name)) + { + return Convert.ToDouble(item.FieldValue); + } + else if (item.CSharpTypeName.EqualCase(UtilConstants.DateType.Name)) + { + return Convert.ToDateTime(item.FieldValue); + } + else if (item.CSharpTypeName.EqualCase(UtilConstants.IntType.Name)) + { + return Convert.ToInt32(item.FieldValue); + } + else if (item.FieldValue != null && item.CSharpTypeName.EqualCase(UtilConstants.BoolType.Name)) + { + return Convert.ToBoolean(item.FieldValue.ToLower()); + } + else if (item.CSharpTypeName.EqualCase(UtilConstants.LongType.Name)) + { + return Convert.ToInt64(item.FieldValue); + } + else if (item.CSharpTypeName.EqualCase(UtilConstants.ShortType.Name)) + { + return Convert.ToInt16(item.FieldValue); + } + else if (item.CSharpTypeName.EqualCase(UtilConstants.DateTimeOffsetType.Name)) + { + DateTimeOffset dt; + if (DateTimeOffset.TryParse(item.FieldValue, out dt)) + { + return dt; + } + return UtilMethods.GetDateTimeOffsetByDateTime(Convert.ToDateTime(item.FieldValue)); + } + else if (item.CSharpTypeName.EqualCase(UtilConstants.GuidType.Name)) + { + return Guid.Parse(item.FieldValue); + } + else if (item.CSharpTypeName.EqualCase("int")) + { + return Convert.ToInt32(item.FieldValue); + } + else if (item.CSharpTypeName.EqualCase("long")) + { + return Convert.ToInt64(item.FieldValue); + } + else if (item.CSharpTypeName.EqualCase("float")) + { + return Convert.ToSingle(item.FieldValue); + } + else if (item.CSharpTypeName.EqualCase("single")) + { + return Convert.ToSingle(item.FieldValue); + } + else if (item.CSharpTypeName.EqualCase("short")) + { + return Convert.ToInt16(item.FieldValue); + } + else if (item.CSharpTypeName.EqualCase("byte")) + { + return Convert.ToByte(item.FieldValue); + } + else if (item.CSharpTypeName.EqualCase("uint")) + { + return Convert.ToUInt32(item.FieldValue); + } + else if (item.CSharpTypeName.EqualCase("ulong")) + { + return Convert.ToUInt64(item.FieldValue); + } + else if (item.CSharpTypeName.EqualCase("ushort")) + { + return Convert.ToUInt16(item.FieldValue); + } + else if (item.CSharpTypeName.EqualCase("uint32")) + { + return Convert.ToUInt32(item.FieldValue); + } + else if (item.CSharpTypeName.EqualCase("uint64")) + { + return Convert.ToUInt64(item.FieldValue); + } + else if (item.CSharpTypeName.EqualCase("bool")) + { + return Convert.ToBoolean(item.FieldValue); + } + else if (item.CSharpTypeName.EqualCase("ToBoolean")) + { + return Convert.ToBoolean(item.FieldValue); + } + else if (item.CSharpTypeName.EqualCase("uint16")) + { + return Convert.ToUInt16(item.FieldValue); + } + else if (item.CSharpTypeName.EqualCase("byte[]") && item.FieldValue != null && item.FieldValue.Contains("|")) + { + return item.FieldValue.Split('|').Select(it => Convert.ToByte(it)).ToArray(); + } + else + { + return item.FieldValue; + } + } + + public static bool IsNumber(string ctypename) + { + if (ctypename.IsNullOrEmpty()) + { + return false; + } + var item = new ConditionalModel() + { + CSharpTypeName = ctypename, + }; + if (item.CSharpTypeName.EqualCase(UtilConstants.DecType.Name)) + { + return true; + } + else if (item.CSharpTypeName.EqualCase(UtilConstants.DobType.Name)) + { + return true; + } + else if (item.CSharpTypeName.EqualCase(UtilConstants.IntType.Name)) + { + return true; + } + else if (item.CSharpTypeName.EqualCase(UtilConstants.LongType.Name)) + { + return true; + } + else if (item.CSharpTypeName.EqualCase(UtilConstants.ShortType.Name)) + { + return true; + } + else if (item.CSharpTypeName.EqualCase("int")) + { + return true; + } + else if (item.CSharpTypeName.EqualCase("long")) + { + return true; + } + else if (item.CSharpTypeName.EqualCase("short")) + { + return true; + } + else if (item.CSharpTypeName.EqualCase("byte")) + { + return true; + } + else if (item.CSharpTypeName.EqualCase("uint")) + { + return true; + } + else if (item.CSharpTypeName.EqualCase("ulong")) + { + return true; + } + else if (item.CSharpTypeName.EqualCase("ushort")) + { + return true; + } + else if (item.CSharpTypeName.EqualCase("uint32")) + { + return true; + } + else if (item.CSharpTypeName.EqualCase("uint64")) + { + return true; + } + else if (item.CSharpTypeName.EqualCase("uint16")) + { + return true; + } + else + { + return false; + } + } + + /// + /// Get Week Last Day Sun + /// + /// + /// + public static DateTime GetWeekLastDaySun(DateTime datetime) + { + //星期天为最后一天 + int weeknow = Convert.ToInt32(datetime.DayOfWeek); + weeknow = (weeknow == 0 ? 7 : weeknow); + int daydiff = (7 - weeknow); + + //本周最后一天 + string LastDay = datetime.AddDays(daydiff).ToString("yyyy-MM-dd"); + return Convert.ToDateTime(LastDay); + } + /// + /// Get Week First Day Mon + /// + /// + /// + public static DateTime GetWeekFirstDayMon(DateTime datetime) + { + //星期一为第一天 + int weeknow = Convert.ToInt32(datetime.DayOfWeek); + + //因为是以星期一为第一天,所以要判断weeknow等于0时,要向前推6天。 + weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1)); + int daydiff = (-1) * weeknow; + + //本周第一天 + string FirstDay = datetime.AddDays(daydiff).ToString("yyyy-MM-dd"); + return Convert.ToDateTime(FirstDay); + } + public static string GetSqlString(DbType dbType, string sql, SugarParameter[] parametres, bool DisableNvarchar = false) + { + if (parametres == null) + parametres = new SugarParameter[] { }; + return GetSqlString(new ConnectionConfig() + { + DbType = dbType, + MoreSettings = new ConnMoreSettings() + { + DisableNvarchar = DisableNvarchar + } + }, new KeyValuePair>(sql, parametres.ToList())); + } + public static string GetSqlString(ConnectionConfig connectionConfig, KeyValuePair> sqlObj) + { + var guid = Guid.NewGuid() + ""; + var result = sqlObj.Key; + if (sqlObj.Value != null) + { + foreach (var item in UtilMethods.CopySugarParameters(sqlObj.Value).OrderByDescending(it => it.ParameterName.Length)) + { + if (item.ParameterName.StartsWith(":") && !result.Contains(item.ParameterName)) + { + item.ParameterName = "@" + item.ParameterName.TrimStart(':'); + } + if (connectionConfig.MoreSettings == null) + { + connectionConfig.MoreSettings = new ConnMoreSettings(); + } + if (item.Value != null && item.Value is DateTime && ((DateTime)item.Value == DateTime.MinValue)) + { + item.Value = connectionConfig.MoreSettings.DbMinDate; + } + if (item.Value == null || item.Value == DBNull.Value) + { + result = result.Replace(item.ParameterName, "null"); + } + else if (UtilMethods.IsNumber(item.Value.GetType().Name)) + { + result = result.Replace(item.ParameterName, item.Value.ObjToString()); + } + else if (item.Value is DateTime && connectionConfig.DbType == DbType.SqlServer) + { + result = result.Replace(item.ParameterName, "CAST('" + item.Value.ObjToDate().ToString("yyyy-MM-dd HH:mm:ss.fff") + "' AS DATETIME)"); + } + else if (item.Value is DateTime && connectionConfig.DbType.IsIn(DbType.Dm, DbType.Oracle)) + { + if (item.DbType == System.Data.DbType.Date || connectionConfig?.MoreSettings?.DisableMillisecond == true) + { + var value = "to_date('" + item.Value.ObjToDate().ToString("yyyy-MM-dd HH:mm:ss") + "', 'YYYY-MM-DD HH24:MI:SS') "; ; + result = result.Replace(item.ParameterName, value); + } + else + { + var value = "to_timestamp('" + item.Value.ObjToDate().ToString("yyyy-MM-dd HH:mm:ss.ffffff") + "', 'YYYY-MM-DD HH24:MI:SS.FF') "; + result = result.Replace(item.ParameterName, value); + } + } + else if (item.Value is DateTime) + { + result = result.Replace(item.ParameterName, "'" + item.Value.ObjToDate().ToString("yyyy-MM-dd HH:mm:ss.fff") + "'"); + } + else if (item.IsArray) + { + result = result.Replace(item.ParameterName, "'{" + new SerializeService().SerializeObject(item.Value).TrimStart('[').TrimEnd(']') + "}'"); + } + else if (item.Value is byte[] && connectionConfig.DbType == DbType.PostgreSQL) + { + result = result.Replace(item.ParameterName, ByteArrayToPostgreByteaLiteral(item.Value as byte[])); + } + else if (item.Value is byte[]) + { + result = result.Replace(item.ParameterName, "0x" + BitConverter.ToString((byte[])item.Value).Replace("-", "")); + } + else if (item.Value is bool) + { + if (connectionConfig.DbType == DbType.PostgreSQL) + { + result = result.Replace(item.ParameterName, (Convert.ToBoolean(item.Value) ? "true" : "false")); + } + else + { + result = result.Replace(item.ParameterName, (Convert.ToBoolean(item.Value) ? 1 : 0) + ""); + } + } + else if (item.Value.GetType() != UtilConstants.StringType && connectionConfig.DbType == DbType.PostgreSQL && PostgreSQLDbBind.MappingTypesConst.Any(x => x.Value.ToString().EqualCase(item.Value.GetType().Name))) + { + var type = PostgreSQLDbBind.MappingTypesConst.First(x => x.Value.ToString().EqualCase(item.Value.GetType().Name)).Key; + var replaceValue = string.Format("CAST('{0}' AS {1})", item.Value, type); + result = result.Replace(item.ParameterName, replaceValue); + } + else if (connectionConfig.MoreSettings?.DisableNvarchar == true || item.DbType == System.Data.DbType.AnsiString || connectionConfig.DbType == DbType.Sqlite) + { + result = result.Replace(item.ParameterName, $"'{item.Value.ObjToString().Replace("@", guid).ToSqlFilter()}'"); + } + else + { + result = result.Replace(item.ParameterName, $"N'{item.Value.ObjToString().Replace("@", guid).ToSqlFilter()}'"); + } + } + } + result = result.Replace(guid, "@"); + return result; + } + public static string ByteArrayToPostgreByteaLiteral(byte[] data) + { + var sb = new StringBuilder("E'"); + + foreach (var b in data) + { + if (b >= 32 && b < 127 && !char.IsControl((char)b)) // 可打印的ASCII字符 + { + sb.Append((char)b); + } + else // 非打印字符或控制字符 + { + sb.Append("\\\\"); + sb.Append(Convert.ToString(b, 8).PadLeft(3, '0')); + } + } + + sb.Append("'::bytea"); + return sb.ToString(); + } + public static void CheckArray(T[] insertObjs) where T : class, new() + { + + if (insertObjs != null + && insertObjs.Length == 1 + && insertObjs.FirstOrDefault() != null + && insertObjs.FirstOrDefault().GetType().FullName.Contains("System.Collections.Generic.List`")) + { + Check.ExceptionEasy("Insertable(T []) is an array and your argument is a List", "二次封装引起的进错重载,当前方法是 Insertable(T []) 参数是一个数组,而你的参数是一个List"); + } + } + + [Obsolete("请使用新名字:FieldNameSql")] + public static string FiledNameSql() + { + return $"[value=sql{UtilConstants.ReplaceKey}]"; + } + public static string FieldNameSql() + { + if (StaticConfig.TableQuerySqlKey != null && StaticConfig.TableQuerySqlKey != Guid.Empty) + { + return $"[value=sql{StaticConfig.TableQuerySqlKey}]"; + } + return $"[value=sql{UtilConstants.ReplaceKey}]"; + } + + internal static object TimeOnlyToTimeSpan(object value) + { + if (value == null) return null; + var method = value.GetType().GetMethods().First(it => it.GetParameters().Length == 0 && it.Name == "ToTimeSpan"); + return method.Invoke(value, new object[] { }); + } + + internal static object DateOnlyToDateTime(object value) + { + if (value == null) return null; + var method = value.GetType().GetMethods().First(it => it.GetParameters().Length == 0 && it.Name == "ToShortDateString"); + return method.Invoke(value, new object[] { }); + } + internal static object DateTimeToDateOnly(object value) + { + if (value == null) return null; + + // 获取DateOnly类型 + Type dateOnlyType = Type.GetType("System.DateOnly, System.Runtime", throwOnError: false); + if (dateOnlyType == null) + { + throw new InvalidOperationException("DateOnly type not found."); + } + + // 获取DateOnly的构造函数 + var constructor = dateOnlyType.GetConstructor(new[] { typeof(int), typeof(int), typeof(int) }); + if (constructor == null) + { + throw new InvalidOperationException("DateOnly constructor not found."); + } + + // 使用反射调用DateTime的属性 + var yearProperty = value.GetType().GetProperty("Year"); + var monthProperty = value.GetType().GetProperty("Month"); + var dayProperty = value.GetType().GetProperty("Day"); + + if (yearProperty == null || monthProperty == null || dayProperty == null) + { + throw new InvalidOperationException("DateTime properties not found."); + } + + int year = (int)yearProperty.GetValue(value); + int month = (int)monthProperty.GetValue(value); + int day = (int)dayProperty.GetValue(value); + + // 使用反射创建DateOnly实例 + return constructor.Invoke(new object[] { year, month, day }); + } + + + internal static void AddDiscrimator(Type type, ISugarQueryable queryable, string shortName = null) + { + var entityInfo = queryable.Context?.EntityMaintenance?.GetEntityInfoWithAttr(type); + if (entityInfo != null && entityInfo.Discrimator.HasValue()) + { + Check.ExceptionEasy(!Regex.IsMatch(entityInfo.Discrimator, @"^(?:\w+:\w+)(?:,\w+:\w+)*$"), "The format should be type:cat for this type, and if there are multiple, it can be FieldName:cat,FieldName2:dog ", "格式错误应该是type:cat这种格式,如果是多个可以FieldName:cat,FieldName2:dog,不要有空格"); + var array = entityInfo.Discrimator.Split(','); + foreach (var disItem in array) + { + var name = disItem.Split(':').First(); + var value = disItem.Split(':').Last(); + queryable.Where(shortName + name, "=", value); + } + } + } + internal static string GetDiscrimator(EntityInfo entityInfo, ISqlBuilder builer) + { + List wheres = new List(); + if (entityInfo != null && entityInfo.Discrimator.HasValue()) + { + Check.ExceptionEasy(!Regex.IsMatch(entityInfo.Discrimator, @"^(?:\w+:\w+)(?:,\w+:\w+)*$"), "The format should be type:cat for this type, and if there are multiple, it can be FieldName:cat,FieldName2:dog ", "格式错误应该是type:cat这种格式,如果是多个可以FieldName:cat,FieldName2:dog,不要有空格"); + var array = entityInfo.Discrimator.Split(','); + foreach (var disItem in array) + { + var name = disItem.Split(':').First(); + var value = disItem.Split(':').Last(); + wheres.Add($"{builer.GetTranslationColumnName(name)}={value.ToSqlValue()} "); + } + } + return string.Join(" AND ", wheres); + } + + internal static bool NoErrorParameter(string parameterName) + { + if (parameterName == null) + { + return false; + } + if (parameterName.Contains(" ")) + { + return false; + } + if (parameterName.Contains("(")) + { + return false; + } + if (parameterName.Contains("(")) + { + return false; + } + if (parameterName.Contains(".")) + { + return false; + } + return true; + } + + internal static ConnMoreSettings GetMoreSetting(ExpressionContext context) + { + return context?.SugarContext?.Context?.CurrentConnectionConfig?.MoreSettings ?? new ConnMoreSettings(); + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/ValidateExtensions.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/ValidateExtensions.cs new file mode 100644 index 0000000000000000000000000000000000000000..75fa9fbef038767a5104a8bd99410fefc54f2ed4 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Tools/ValidateExtensions.cs @@ -0,0 +1,171 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +namespace SqlSugar.TDSQLForOracleODBC +{ + internal static class ValidateExtensions + { + public static bool IsInRange(this int thisValue, int begin, int end) + { + return thisValue >= begin && thisValue <= end; + } + + public static bool IsInRange(this DateTime thisValue, DateTime begin, DateTime end) + { + return thisValue >= begin && thisValue <= end; + } + + public static bool IsIn(this T thisValue, params T[] values) + { + return values.Contains(thisValue); + } + + public static bool IsContainsIn(this string thisValue, params string[] inValues) + { + return inValues.Any(it => thisValue.Contains(it)); + } + + public static bool IsNullOrEmpty(this object thisValue) + { + if (thisValue == null || thisValue == DBNull.Value) return true; + return thisValue.ToString() == ""; + } + + public static bool IsNullOrEmpty(this Guid? thisValue) + { + if (thisValue == null) return true; + return thisValue == Guid.Empty; + } + + public static bool IsNullOrEmpty(this Guid thisValue) + { + if (thisValue == null) return true; + return thisValue == Guid.Empty; + } + + public static bool IsNullOrEmpty(this IEnumerable thisValue) + { + if (thisValue == null || thisValue.Count() == 0) return true; + return false; + } + + public static bool HasValue(this object thisValue) + { + if (thisValue == null || thisValue == DBNull.Value) return false; + return thisValue.ToString() != ""; + } + + public static bool HasValue(this IEnumerable thisValue) + { + if (thisValue == null || thisValue.Count() == 0) return false; + return true; + } + + public static bool IsValuable(this IEnumerable> thisValue) + { + if (thisValue == null || thisValue.Count() == 0) return false; + return true; + } + + public static bool IsZero(this object thisValue) + { + return (thisValue == null || thisValue.ToString() == "0"); + } + + public static bool IsInt(this object thisValue) + { + if (thisValue == null) return false; + return Regex.IsMatch(thisValue.ToString(), @"^\d+$"); + } + + /// + public static bool IsNoInt(this object thisValue) + { + if (thisValue == null) return true; + return !Regex.IsMatch(thisValue.ToString(), @"^\d+$"); + } + + public static bool IsMoney(this object thisValue) + { + if (thisValue == null) return false; + double outValue = 0; + return double.TryParse(thisValue.ToString(), out outValue); + } + public static bool IsGuid(this object thisValue) + { + if (thisValue == null) return false; + Guid outValue = Guid.Empty; + return Guid.TryParse(thisValue.ToString(), out outValue); + } + + public static bool IsDate(this object thisValue) + { + if (thisValue == null) return false; + DateTime outValue = DateTime.MinValue; + return DateTime.TryParse(thisValue.ToString(), out outValue); + } + + public static bool IsEamil(this object thisValue) + { + if (thisValue == null) return false; + return Regex.IsMatch(thisValue.ToString(), @"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$"); + } + + public static bool IsMobile(this object thisValue) + { + if (thisValue == null) return false; + return Regex.IsMatch(thisValue.ToString(), @"^\d{11}$"); + } + + public static bool IsTelephone(this object thisValue) + { + if (thisValue == null) return false; + return System.Text.RegularExpressions.Regex.IsMatch(thisValue.ToString(), @"^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{8}$"); + + } + + public static bool IsIDcard(this object thisValue) + { + if (thisValue == null) return false; + return System.Text.RegularExpressions.Regex.IsMatch(thisValue.ToString(), @"^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$"); + } + + public static bool IsFax(this object thisValue) + { + if (thisValue == null) return false; + return System.Text.RegularExpressions.Regex.IsMatch(thisValue.ToString(), @"^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$"); + } + + public static bool IsMatch(this object thisValue, string pattern) + { + if (thisValue == null) return false; + Regex reg = new Regex(pattern); + return reg.IsMatch(thisValue.ToString()); + } + public static bool IsAnonymousType(this Type type) + { + string typeName = type.Name; + return typeName.Contains("<>") && typeName.Contains("__") && typeName.Contains("AnonymousType"); + } + public static bool IsCollectionsList(this string thisValue) + { + return (thisValue + "").StartsWith("System.Collections.Generic.List") || (thisValue + "").StartsWith("System.Collections.Generic.IEnumerable"); + } + public static bool IsStringArray(this string thisValue) + { + return (thisValue + "").IsMatch(@"System\.[a-z,A-Z,0-9]+?\[\]"); + } + public static bool IsEnumerable(this string thisValue) + { + return (thisValue + "").StartsWith("System.Linq.Enumerable"); + } + + public static Type StringType = typeof(string); + + public static bool IsClass(this Type thisValue) + { + return thisValue != StringType && thisValue.IsEntity() && thisValue != UtilConstants.ByteArrayType; + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Utilities/UtilConvert.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Utilities/UtilConvert.cs new file mode 100644 index 0000000000000000000000000000000000000000..171d9abb93ed79ba4ea0259bb7507aa44a2e2d19 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForOracleODBC/Utilities/UtilConvert.cs @@ -0,0 +1,189 @@ +using System; +using System.Linq.Expressions; +namespace SqlSugar.TDSQLForOracleODBC +{ + internal static class UtilConvert + { + public static int ObjToInt(this object thisValue) + { + int reval = 0; + if (thisValue == null) return 0; + if (thisValue is Enum) + { + return Convert.ToInt32(thisValue); + } + if (thisValue != null && thisValue != DBNull.Value && int.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + return reval; + } + + public static long ObjToLong(this object thisValue) + { + long reval = 0; + if (thisValue == null) return 0; + if (thisValue is Enum) + { + return Convert.ToInt64(thisValue); + } + if (thisValue != null && thisValue != DBNull.Value && long.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + return reval; + } + + public static int ObjToInt(this object thisValue, int errorValue) + { + int reval = 0; + if (thisValue is Enum) + { + return (int)thisValue; + } + if (thisValue != null && thisValue != DBNull.Value && int.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + return errorValue; + } + + public static double ObjToMoney(this object thisValue) + { + double reval = 0; + if (thisValue != null && thisValue != DBNull.Value && double.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + return 0; + } + + public static double ObjToMoney(this object thisValue, double errorValue) + { + double reval = 0; + if (thisValue != null && thisValue != DBNull.Value && double.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + return errorValue; + } + public static bool EqualCase(this string thisValue, string equalValue) + { + if (thisValue != null && equalValue != null) + { + return thisValue.ToLower() == equalValue.ToLower(); + } + else + { + return thisValue == equalValue; + } + } + public static string ObjToString(this object thisValue, Func formatTime) + { + if (formatTime != null && thisValue is DateTime) + { + var dt = Convert.ToDateTime(thisValue); + return formatTime(dt); + } + else + { + return thisValue.ObjToStringNoTrim(); + } + } + public static string ObjToString(this object thisValue) + { + if (thisValue != null) return thisValue.ToString().Trim(); + return ""; + } + public static string ObjToStringNoTrim(this object thisValue) + { + if (thisValue != null) return thisValue.ToString(); + return ""; + } + public static string ObjToStringNew(this object thisValue) + { + if (thisValue != null && thisValue is byte[]) + { + return string.Join("|", thisValue as byte[]); + } + if (thisValue != null) return thisValue.ToString().Trim(); + return ""; + } + + public static string ObjToString(this object thisValue, string errorValue) + { + if (thisValue != null) return thisValue.ToString().Trim(); + return errorValue; + } + + public static Decimal ObjToDecimal(this object thisValue) + { + Decimal reval = 0; + if (thisValue != null && thisValue != DBNull.Value && decimal.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + return 0; + } + + public static Decimal ObjToDecimal(this object thisValue, decimal errorValue) + { + Decimal reval = 0; + if (thisValue != null && thisValue != DBNull.Value && decimal.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + return errorValue; + } + + public static DateTime ObjToDate(this object thisValue) + { + if (thisValue is DateTime) + { + return (DateTime)thisValue; + } + DateTime reval = DateTime.MinValue; + if (thisValue != null && thisValue != DBNull.Value && DateTime.TryParse(thisValue.ToString(), out reval)) + { + reval = Convert.ToDateTime(thisValue); + } + return reval; + } + + public static DateTime ObjToDate(this object thisValue, DateTime errorValue) + { + if (thisValue is DateTime) + { + return (DateTime)thisValue; + } + DateTime reval = DateTime.MinValue; + if (thisValue != null && thisValue != DBNull.Value && DateTime.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + return errorValue; + } + + public static bool ObjToBool(this object thisValue) + { + bool reval = false; + if (thisValue != null && thisValue != DBNull.Value && bool.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + return reval; + } + + internal static MemberExpression ToMemberExpression(Expression parentIdExpression) + { + if (parentIdExpression is UnaryExpression) + { + return (parentIdExpression as UnaryExpression).Operand as MemberExpression; + } + else + { + return parentIdExpression as MemberExpression; + } + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.TDSQLForPGODBC/TDSQLForPG/DbBind/TDSQLForPGODBCDbBind.cs b/Src/Asp.NetCore2/SqlSugar.TDSQLForPGODBC/TDSQLForPG/DbBind/TDSQLForPGODBCDbBind.cs index 571cb482b63885405632f3b2df80ba68582b09f5..d26f44ccbf28674d9096653a285dd150e78d20a8 100644 --- a/Src/Asp.NetCore2/SqlSugar.TDSQLForPGODBC/TDSQLForPG/DbBind/TDSQLForPGODBCDbBind.cs +++ b/Src/Asp.NetCore2/SqlSugar.TDSQLForPGODBC/TDSQLForPG/DbBind/TDSQLForPGODBCDbBind.cs @@ -50,6 +50,10 @@ namespace SqlSugar.TDSQLForPGODBC dbTypeName = dbTypeName.ToLower(); dbTypeName = GetValidCsharpTypeName(dbTypeName); var propertyTypes = MappingTypes.Where(it => it.Value.ToString().ToLower() == dbTypeName || it.Key.ToLower() == dbTypeName); + if (dbTypeName == "text") + { + return "other"; + } if (propertyTypes == null || dbTypeName == "unknown") { return "other"; diff --git a/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarAccessory.cs b/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarAccessory.cs index 40b82f0dc42caeec68ef01f754d37668832d90bc..7a81e9faf3888a223161ecb93fd98f8dd57284a4 100644 --- a/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarAccessory.cs +++ b/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarAccessory.cs @@ -501,6 +501,10 @@ namespace SqlSugar Check.Exception(SugarCompatible.IsFramework, "TDSQLForPGODBC only support .net core"); InstanceFactory.CustomDllName = SugarCompatible.IsFramework ? "SqlSugar.TDSQLForPGODBC" : "SqlSugar.TDSQLForPGODBC"; break; + case DbType.TDSQLForOracleODBC: + Check.Exception(SugarCompatible.IsFramework, "TDSQLForOracleODBC only support .net core"); + InstanceFactory.CustomDllName = SugarCompatible.IsFramework ? "SqlSugar.TDSQLForOracleODBC" : "SqlSugar.TDSQLForOracleODBC"; + break; case DbType.GaussDB: config.DbType = DbType.PostgreSQL; if (this.CurrentConnectionConfig.MoreSettings == null) diff --git a/Src/Asp.NetCore2/SqlSugar/Enum/DbType.cs b/Src/Asp.NetCore2/SqlSugar/Enum/DbType.cs index 13704cd3d92a1ad023524159a7c6b83db7254693..3a41105c6554d8a291304ecbf67f64f2ac01a0e7 100644 --- a/Src/Asp.NetCore2/SqlSugar/Enum/DbType.cs +++ b/Src/Asp.NetCore2/SqlSugar/Enum/DbType.cs @@ -7,7 +7,7 @@ namespace SqlSugar { public enum DbType { - MySql , + MySql, SqlServer, Sqlite, Oracle, @@ -33,13 +33,14 @@ namespace SqlSugar Doris, Xugu, GoldenDB, - TDSQLForPGODBC, + TDSQLForPGODBC, + TDSQLForOracleODBC, TDSQL, HANA, DB2, GaussDBNative, DuckDB, MongoDb, - Custom =900 + Custom = 900 } } diff --git a/Src/Asp.NetCore2/SqlSugarCore.sln b/Src/Asp.NetCore2/SqlSugarCore.sln index f2e4d665c9a206bb55caddcc70448529dbe991c0..125d5f25aece6d8f3f44ed47e8347e6c2a5c0cd3 100644 --- a/Src/Asp.NetCore2/SqlSugarCore.sln +++ b/Src/Asp.NetCore2/SqlSugarCore.sln @@ -1,6 +1,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.1.32414.318 +# Visual Studio Version 18 +VisualStudioVersion = 18.6.11822.322 stable MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SqlSeverTest", "SqlSeverTest\SqlSeverTest.csproj", "{B44F2513-E55B-480F-A41C-685DDD083355}" EndProject @@ -109,6 +109,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TDengine.Ado.Data", "TDengi EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PerformanceBenchmarks", "PerformanceBenchmarks\PerformanceBenchmarks.csproj", "{A1B2C3D4-E5F6-4A5B-8C9D-0E1F2A3B4C5D}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SqlSugar.TDSQLForOracleODBC", "SqlSugar.TDSQLForOracleODBC\SqlSugar.TDSQLForOracleODBC.csproj", "{789B91E8-8B09-5CE0-940A-5BE2324B0C08}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "4TDSQLForOracleODBCTest", "4TDSQLForOracleODBCTest\4TDSQLForOracleODBCTest.csproj", "{16D3E36A-2B43-EDEA-635A-243BB6C60D87}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -707,6 +711,30 @@ Global {A1B2C3D4-E5F6-4A5B-8C9D-0E1F2A3B4C5D}.Release|ARM32.Build.0 = Release|Any CPU {A1B2C3D4-E5F6-4A5B-8C9D-0E1F2A3B4C5D}.Release|x86.ActiveCfg = Release|Any CPU {A1B2C3D4-E5F6-4A5B-8C9D-0E1F2A3B4C5D}.Release|x86.Build.0 = Release|Any CPU + {789B91E8-8B09-5CE0-940A-5BE2324B0C08}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {789B91E8-8B09-5CE0-940A-5BE2324B0C08}.Debug|Any CPU.Build.0 = Debug|Any CPU + {789B91E8-8B09-5CE0-940A-5BE2324B0C08}.Debug|ARM32.ActiveCfg = Debug|Any CPU + {789B91E8-8B09-5CE0-940A-5BE2324B0C08}.Debug|ARM32.Build.0 = Debug|Any CPU + {789B91E8-8B09-5CE0-940A-5BE2324B0C08}.Debug|x86.ActiveCfg = Debug|Any CPU + {789B91E8-8B09-5CE0-940A-5BE2324B0C08}.Debug|x86.Build.0 = Debug|Any CPU + {789B91E8-8B09-5CE0-940A-5BE2324B0C08}.Release|Any CPU.ActiveCfg = Release|Any CPU + {789B91E8-8B09-5CE0-940A-5BE2324B0C08}.Release|Any CPU.Build.0 = Release|Any CPU + {789B91E8-8B09-5CE0-940A-5BE2324B0C08}.Release|ARM32.ActiveCfg = Release|Any CPU + {789B91E8-8B09-5CE0-940A-5BE2324B0C08}.Release|ARM32.Build.0 = Release|Any CPU + {789B91E8-8B09-5CE0-940A-5BE2324B0C08}.Release|x86.ActiveCfg = Release|Any CPU + {789B91E8-8B09-5CE0-940A-5BE2324B0C08}.Release|x86.Build.0 = Release|Any CPU + {16D3E36A-2B43-EDEA-635A-243BB6C60D87}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {16D3E36A-2B43-EDEA-635A-243BB6C60D87}.Debug|Any CPU.Build.0 = Debug|Any CPU + {16D3E36A-2B43-EDEA-635A-243BB6C60D87}.Debug|ARM32.ActiveCfg = Debug|Any CPU + {16D3E36A-2B43-EDEA-635A-243BB6C60D87}.Debug|ARM32.Build.0 = Debug|Any CPU + {16D3E36A-2B43-EDEA-635A-243BB6C60D87}.Debug|x86.ActiveCfg = Debug|Any CPU + {16D3E36A-2B43-EDEA-635A-243BB6C60D87}.Debug|x86.Build.0 = Debug|Any CPU + {16D3E36A-2B43-EDEA-635A-243BB6C60D87}.Release|Any CPU.ActiveCfg = Release|Any CPU + {16D3E36A-2B43-EDEA-635A-243BB6C60D87}.Release|Any CPU.Build.0 = Release|Any CPU + {16D3E36A-2B43-EDEA-635A-243BB6C60D87}.Release|ARM32.ActiveCfg = Release|Any CPU + {16D3E36A-2B43-EDEA-635A-243BB6C60D87}.Release|ARM32.Build.0 = Release|Any CPU + {16D3E36A-2B43-EDEA-635A-243BB6C60D87}.Release|x86.ActiveCfg = Release|Any CPU + {16D3E36A-2B43-EDEA-635A-243BB6C60D87}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -730,6 +758,7 @@ Global {9D7D900A-01ED-4E7C-A97A-1D3325F67AA2} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} {47298939-4904-4997-848B-ADB32D4163D0} = {88992AAF-146B-4253-9AD7-493E8F415B57} {14D14094-34AD-9085-1C96-B63177762C10} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {789B91E8-8B09-5CE0-940A-5BE2324B0C08} = {88992AAF-146B-4253-9AD7-493E8F415B57} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {230A85B9-54F1-41B1-B1DA-80086581B2B4}