mirror of
https://gitee.com/dotnetchina/SqlSugar.git
synced 2025-04-05 17:37:58 +08:00
Add Odbc
This commit is contained in:
parent
a3b7d6403c
commit
64822134d9
19
Src/Asp.NetCore2/OdbcTest/Config.cs
Normal file
19
Src/Asp.NetCore2/OdbcTest/Config.cs
Normal file
@ -0,0 +1,19 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
|
||||
public class Config
|
||||
{
|
||||
|
||||
public static string ConnectionString = "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";
|
||||
|
||||
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";
|
||||
|
||||
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";
|
||||
}
|
||||
}
|
58
Src/Asp.NetCore2/OdbcTest/Demo/Demo7_Ado.cs
Normal file
58
Src/Asp.NetCore2/OdbcTest/Demo/Demo7_Ado.cs
Normal file
@ -0,0 +1,58 @@
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class Demo7_Ado
|
||||
{
|
||||
public static void Init()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### Ado Start ####");
|
||||
|
||||
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
DbType = DbType.Odbc,
|
||||
ConnectionString = Config.ConnectionString,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
IsAutoCloseConnection = true,
|
||||
AopEvents = new AopEvents
|
||||
{
|
||||
OnLogExecuting = (sql, p) =>
|
||||
{
|
||||
Console.WriteLine(sql);
|
||||
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
|
||||
}
|
||||
}
|
||||
});
|
||||
//sql
|
||||
var dt = db.Ado.GetDataTable("select * from order where @id>0 or name=@name", new List<SugarParameter>(){
|
||||
new SugarParameter("@id",1),
|
||||
new SugarParameter("@name","2")
|
||||
});
|
||||
|
||||
//sql
|
||||
var dt2 = db.Ado.GetDataTable("select * from order where @id>0 or name=@name", new { id = 1, name = "2" });
|
||||
|
||||
//Stored Procedure
|
||||
//var dt3 = db.Ado.UseStoredProcedure().GetDataTable("sp_school", new { name = "张三", age = 0 });
|
||||
//var nameP = new SugarParameter("@name", "张三");
|
||||
//var ageP = new SugarParameter("@age", null, true);//isOutput=true
|
||||
//var dt4 = db.Ado.UseStoredProcedure().GetDataTable("sp_school", nameP, ageP);
|
||||
|
||||
|
||||
|
||||
//There are many methods to under db.ado
|
||||
var list= db.Ado.SqlQuery<Order>("select * from order ");
|
||||
var intValue=db.Ado.SqlQuerySingle<int>("select 1 from dual");
|
||||
db.Ado.ExecuteCommand("delete from order where id>1000");
|
||||
db.Ado.ExecuteCommand($"delete from order where id>1000");
|
||||
//db.Ado.xxx
|
||||
Console.WriteLine("#### Ado End ####");
|
||||
}
|
||||
}
|
||||
}
|
20
Src/Asp.NetCore2/OdbcTest/Models/AttributeTable.cs
Normal file
20
Src/Asp.NetCore2/OdbcTest/Models/AttributeTable.cs
Normal file
@ -0,0 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
[Table("MyAttributeTable")]
|
||||
//[SugarTable("CustomAttributeTable")]
|
||||
public class AttributeTable
|
||||
{
|
||||
|
||||
[Key]
|
||||
//[SugarColumn(IsPrimaryKey =true)]
|
||||
public string Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
}
|
||||
}
|
7
Src/Asp.NetCore2/OdbcTest/Models/CarType.cs
Normal file
7
Src/Asp.NetCore2/OdbcTest/Models/CarType.cs
Normal file
@ -0,0 +1,7 @@
|
||||
namespace OrmTest
|
||||
{
|
||||
public class CarType
|
||||
{
|
||||
public bool State { get; set; }
|
||||
}
|
||||
}
|
14
Src/Asp.NetCore2/OdbcTest/Models/Custom.cs
Normal file
14
Src/Asp.NetCore2/OdbcTest/Models/Custom.cs
Normal file
@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class Custom
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
}
|
||||
}
|
15
Src/Asp.NetCore2/OdbcTest/Models/EntityMapper.cs
Normal file
15
Src/Asp.NetCore2/OdbcTest/Models/EntityMapper.cs
Normal file
@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using SqlSugar;
|
||||
namespace OrmTest
|
||||
{
|
||||
[SugarTable("MyEntityMapper")]
|
||||
public class EntityMapper
|
||||
{
|
||||
[SugarColumn(ColumnName ="MyName")]
|
||||
public string Name { get; set; }
|
||||
}
|
||||
}
|
54
Src/Asp.NetCore2/OdbcTest/Models/Mapper.cs
Normal file
54
Src/Asp.NetCore2/OdbcTest/Models/Mapper.cs
Normal file
@ -0,0 +1,54 @@
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
[SugarTable("OrderDetail")]
|
||||
public class OrderItemInfo
|
||||
{
|
||||
[SqlSugar.SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
|
||||
public int ItemId { get; set; }
|
||||
public int OrderId { get; set; }
|
||||
public decimal? Price { get; set; }
|
||||
[SqlSugar.SugarColumn(IsNullable = true)]
|
||||
public DateTime? CreateTime { get; set; }
|
||||
[SugarColumn(IsIgnore = true)]
|
||||
public Order Order { get; set; }
|
||||
}
|
||||
[SugarTable("Order")]
|
||||
public class OrderInfo
|
||||
{
|
||||
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
[SugarColumn(IsIgnore = true)]
|
||||
public List<OrderItem> Items { get; set; }
|
||||
}
|
||||
public class ABMapping
|
||||
{
|
||||
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
|
||||
public int AId { get; set; }
|
||||
public int BId { get; set; }
|
||||
[SugarColumn(IsIgnore = true)]
|
||||
public A A { get; set; }
|
||||
[SugarColumn(IsIgnore = true)]
|
||||
public B B { get; set; }
|
||||
|
||||
}
|
||||
public class A
|
||||
{
|
||||
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
}
|
||||
public class B
|
||||
{
|
||||
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
}
|
||||
}
|
20
Src/Asp.NetCore2/OdbcTest/Models/MyCustomAttributeTable.cs
Normal file
20
Src/Asp.NetCore2/OdbcTest/Models/MyCustomAttributeTable.cs
Normal file
@ -0,0 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
[Table("CustomAttributeTable")]
|
||||
//[SugarTable("CustomAttributeTable")]
|
||||
public class MyCustomAttributeTable
|
||||
{
|
||||
|
||||
[Key]
|
||||
//[SugarColumn(IsPrimaryKey =true)]
|
||||
public string Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
}
|
||||
}
|
24
Src/Asp.NetCore2/OdbcTest/Models/Order.cs
Normal file
24
Src/Asp.NetCore2/OdbcTest/Models/Order.cs
Normal file
@ -0,0 +1,24 @@
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
|
||||
public class Order
|
||||
{
|
||||
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
|
||||
public int Id { get; set; }
|
||||
|
||||
public string Name { get; set; }
|
||||
public decimal Price { get; set; }
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public DateTime CreateTime { get; set; }
|
||||
[SugarColumn(IsNullable =true)]
|
||||
public int CustomId { get; set; }
|
||||
[SugarColumn(IsIgnore = true)]
|
||||
public List<OrderItem> Items { get; set; }
|
||||
}
|
||||
}
|
18
Src/Asp.NetCore2/OdbcTest/Models/OrderItem.cs
Normal file
18
Src/Asp.NetCore2/OdbcTest/Models/OrderItem.cs
Normal file
@ -0,0 +1,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
[SqlSugar.SugarTable("OrderDetail")]
|
||||
public class OrderItem
|
||||
{
|
||||
[SqlSugar.SugarColumn(IsPrimaryKey =true, IsIdentity =true)]
|
||||
public int ItemId { get; set; }
|
||||
public int OrderId { get; set; }
|
||||
public decimal? Price { get; set; }
|
||||
[SqlSugar.SugarColumn(IsNullable = true)]
|
||||
public DateTime? CreateTime { get; set; }
|
||||
}
|
||||
}
|
17
Src/Asp.NetCore2/OdbcTest/Models/TestTree.cs
Normal file
17
Src/Asp.NetCore2/OdbcTest/Models/TestTree.cs
Normal file
@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class TestTree
|
||||
{
|
||||
[SqlSugar.SugarColumn(ColumnDataType = "hierarchyid")]
|
||||
public string TreeId { get; set; }
|
||||
[SqlSugar.SugarColumn(ColumnDataType = "Geography")]
|
||||
public string GId { get; set; }
|
||||
public string Name { get; set; }
|
||||
}
|
||||
}
|
20
Src/Asp.NetCore2/OdbcTest/Models/Tree.cs
Normal file
20
Src/Asp.NetCore2/OdbcTest/Models/Tree.cs
Normal file
@ -0,0 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class Tree
|
||||
{
|
||||
[SqlSugar.SugarColumn(IsPrimaryKey =true)]
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
public int ParentId { get; set; }
|
||||
[SqlSugar.SugarColumn(IsIgnore = true)]
|
||||
public Tree Parent { get; set; }
|
||||
[SqlSugar.SugarColumn(IsIgnore = true)]
|
||||
public List<Tree> Child { get; set; }
|
||||
}
|
||||
}
|
13
Src/Asp.NetCore2/OdbcTest/Models/ViewOrder.cs
Normal file
13
Src/Asp.NetCore2/OdbcTest/Models/ViewOrder.cs
Normal file
@ -0,0 +1,13 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class ViewOrder:Order
|
||||
{
|
||||
public string CustomName { get; set; }
|
||||
}
|
||||
}
|
13
Src/Asp.NetCore2/OdbcTest/OdbcTest.csproj
Normal file
13
Src/Asp.NetCore2/OdbcTest/OdbcTest.csproj
Normal file
@ -0,0 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>netcoreapp3.1</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\SqlSugar.OdbcCore\SqlSugar.OdbcCore.csproj" />
|
||||
<ProjectReference Include="..\SqlSugar\SqlSugar.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
14
Src/Asp.NetCore2/OdbcTest/Program.cs
Normal file
14
Src/Asp.NetCore2/OdbcTest/Program.cs
Normal file
@ -0,0 +1,14 @@
|
||||
using OrmTest;
|
||||
using System;
|
||||
|
||||
namespace GbaseTest
|
||||
{
|
||||
internal class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
Demo7_Ado.Init();
|
||||
Console.WriteLine("Hello World!");
|
||||
}
|
||||
}
|
||||
}
|
9
Src/Asp.NetCore2/SqlSugar.OdbcCore/Class1.cs
Normal file
9
Src/Asp.NetCore2/SqlSugar.OdbcCore/Class1.cs
Normal file
@ -0,0 +1,9 @@
|
||||
using System;
|
||||
|
||||
namespace SqlSugar.OdbcCore
|
||||
{
|
||||
public class Class1
|
||||
{
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,157 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.Odbc;
|
||||
using System.Text;
|
||||
namespace SqlSugar.Odbc
|
||||
{
|
||||
/// <summary>
|
||||
/// 数据填充器
|
||||
/// </summary>
|
||||
public class OdbcDataAdapter : IDataAdapter
|
||||
{
|
||||
private OdbcCommand command;
|
||||
private string sql;
|
||||
private OdbcConnection _sqlConnection;
|
||||
|
||||
/// <summary>
|
||||
/// SqlDataAdapter
|
||||
/// </summary>
|
||||
/// <param name="command"></param>
|
||||
public OdbcDataAdapter(OdbcCommand command)
|
||||
{
|
||||
this.command = command;
|
||||
}
|
||||
|
||||
public OdbcDataAdapter()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SqlDataAdapter
|
||||
/// </summary>
|
||||
/// <param name="sql"></param>
|
||||
/// <param name="_sqlConnection"></param>
|
||||
public OdbcDataAdapter(string sql, OdbcConnection _sqlConnection)
|
||||
{
|
||||
this.sql = sql;
|
||||
this._sqlConnection = _sqlConnection;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SelectCommand
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fill
|
||||
/// </summary>
|
||||
/// <param name="dt"></param>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fill
|
||||
/// </summary>
|
||||
/// <param name="ds"></param>
|
||||
public void Fill(DataSet ds)
|
||||
{
|
||||
if (ds == null)
|
||||
{
|
||||
ds = new DataSet();
|
||||
}
|
||||
using (var dr = command.ExecuteReader())
|
||||
{
|
||||
do
|
||||
{
|
||||
var dt = new DataTable();
|
||||
var columns = dt.Columns;
|
||||
var rows = dt.Rows;
|
||||
for (int i = 0; i < dr.FieldCount; i++)
|
||||
{
|
||||
string name = dr.GetName(i).Trim();
|
||||
if (dr.GetFieldType(i).Name == "DateTime")
|
||||
{
|
||||
if (!columns.Contains(name))
|
||||
columns.Add(new DataColumn(name, UtilConstants.DateType));
|
||||
else
|
||||
{
|
||||
columns.Add(new DataColumn(name + i, UtilConstants.DateType));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
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();
|
||||
ds.Tables.Add(dt);
|
||||
} while (dr.NextResult());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
namespace SqlSugar.Odbc
|
||||
{
|
||||
public class OdbcCodeFirst:CodeFirstProvider
|
||||
{
|
||||
public virtual bool IsNoTran { get; set; } = true;
|
||||
public override void ExistLogic(EntityInfo entityInfo)
|
||||
{
|
||||
this.Context.Ado.ExecuteCommand("select '不支持修改表' from dual ");
|
||||
}
|
||||
|
||||
protected override DbColumnInfo EntityColumnToDbColumn(EntityInfo entityInfo, string tableName, EntityColumnInfo item)
|
||||
{
|
||||
var result= base.EntityColumnToDbColumn(entityInfo, tableName, item);
|
||||
if (item.UnderType == UtilConstants.GuidType)
|
||||
{
|
||||
item.Length = 36;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
protected override string GetTableName(EntityInfo entityInfo)
|
||||
{
|
||||
var table= this.Context.EntityMaintenance.GetTableName(entityInfo.EntityName);
|
||||
var tableArray = table.Split('.');
|
||||
var noFormat = table.Split(']').Length==1;
|
||||
if (tableArray.Length > 1 && noFormat)
|
||||
{
|
||||
var dbMain = new OdbcDbMaintenance() { Context = this.Context };
|
||||
return dbMain.SqlBuilder.GetTranslationTableName(table);
|
||||
}
|
||||
else
|
||||
{
|
||||
return table;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,62 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
namespace SqlSugar.Odbc
|
||||
{
|
||||
public class OdbcDbBind : DbBindProvider
|
||||
{
|
||||
public override string GetDbTypeName(string csharpTypeName)
|
||||
{
|
||||
if (csharpTypeName == nameof(DateTimeOffset))
|
||||
{
|
||||
return nameof(DateTimeOffset);
|
||||
}
|
||||
else
|
||||
{
|
||||
return base.GetDbTypeName(csharpTypeName);
|
||||
}
|
||||
}
|
||||
public override List<KeyValuePair<string, CSharpDataType>> 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<KeyValuePair<string, CSharpDataType>> MappingTypesConst = new List<KeyValuePair<string, CSharpDataType>>()
|
||||
{
|
||||
new KeyValuePair<string, CSharpDataType>("bigint",CSharpDataType.@long),
|
||||
new KeyValuePair<string, CSharpDataType>("blob",CSharpDataType.byteArray),
|
||||
new KeyValuePair<string, CSharpDataType>("boolean",CSharpDataType.@bool),
|
||||
new KeyValuePair<string, CSharpDataType>("byte",CSharpDataType.@byte),
|
||||
new KeyValuePair<string, CSharpDataType>("varchar", CSharpDataType.@string),
|
||||
new KeyValuePair<string, CSharpDataType>("char",CSharpDataType.@string),
|
||||
new KeyValuePair<string, CSharpDataType>("clob",CSharpDataType.@string),
|
||||
new KeyValuePair<string, CSharpDataType>("DATETIME YEAR TO FRACTION(3)", CSharpDataType.DateTime),
|
||||
new KeyValuePair<string, CSharpDataType>("datetime", CSharpDataType.DateTime),
|
||||
new KeyValuePair<string, CSharpDataType>("date", CSharpDataType.DateTime),
|
||||
new KeyValuePair<string, CSharpDataType>("decimal", CSharpDataType.@decimal),
|
||||
new KeyValuePair<string, CSharpDataType>("float", CSharpDataType.@float),
|
||||
new KeyValuePair<string, CSharpDataType>("int", CSharpDataType.@int),
|
||||
new KeyValuePair<string, CSharpDataType>("integer", CSharpDataType.@int),
|
||||
new KeyValuePair<string, CSharpDataType>("money", CSharpDataType.@decimal),
|
||||
new KeyValuePair<string, CSharpDataType>("nchar", CSharpDataType.@string),
|
||||
new KeyValuePair<string, CSharpDataType>("numeric", CSharpDataType.@decimal),
|
||||
new KeyValuePair<string, CSharpDataType>("nvarchar", CSharpDataType.@string),
|
||||
new KeyValuePair<string, CSharpDataType>("varchar", CSharpDataType.@string),
|
||||
new KeyValuePair<string, CSharpDataType>("text", CSharpDataType.@string),
|
||||
new KeyValuePair<string, CSharpDataType>("smallfloat", CSharpDataType.@decimal),
|
||||
new KeyValuePair<string, CSharpDataType>("serial", CSharpDataType.@int),
|
||||
};
|
||||
};
|
||||
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace SqlSugar.Odbc
|
||||
{
|
||||
public class OdbcDbFirst : DbFirstProvider
|
||||
{
|
||||
}
|
||||
}
|
@ -0,0 +1,482 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Data.Odbc;
|
||||
namespace SqlSugar.Odbc
|
||||
{
|
||||
public class OdbcDbMaintenance : DbMaintenanceProvider
|
||||
{
|
||||
#region DML
|
||||
protected override string GetDataBaseSql
|
||||
{
|
||||
get
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
protected override string GetColumnInfosByTableNameSql
|
||||
{
|
||||
get
|
||||
{
|
||||
string sql = @"SELECT sysobjects.name AS TableName,
|
||||
syscolumns.Id AS TableId,
|
||||
syscolumns.name AS DbColumnName,
|
||||
systypes.name AS DataType,
|
||||
COLUMNPROPERTY(syscolumns.id,syscolumns.name,'PRECISION') as [length],
|
||||
isnull(COLUMNPROPERTY(syscolumns.id,syscolumns.name,'Scale'),0) as Scale,
|
||||
isnull(COLUMNPROPERTY(syscolumns.id,syscolumns.name,'Scale'),0) as DecimalDigits,
|
||||
sys.extended_properties.[value] AS [ColumnDescription],
|
||||
syscomments.text AS DefaultValue,
|
||||
syscolumns.isnullable AS IsNullable,
|
||||
columnproperty(syscolumns.id,syscolumns.name,'IsIdentity')as IsIdentity,
|
||||
(CASE
|
||||
WHEN EXISTS
|
||||
(
|
||||
select 1
|
||||
from sysindexes i
|
||||
join sysindexkeys k on i.id = k.id and i.indid = k.indid
|
||||
join sysobjects o on i.id = o.id
|
||||
join syscolumns c on i.id=c.id and k.colid = c.colid
|
||||
where o.xtype = 'U'
|
||||
and exists(select 1 from sysobjects where xtype = 'PK' and name = i.name)
|
||||
and o.name=sysobjects.name and c.name=syscolumns.name
|
||||
) THEN 1
|
||||
ELSE 0
|
||||
END) AS IsPrimaryKey
|
||||
FROM syscolumns
|
||||
INNER JOIN systypes ON syscolumns.xtype = systypes.xtype
|
||||
LEFT JOIN sysobjects ON syscolumns.id = sysobjects.id
|
||||
LEFT OUTER JOIN sys.extended_properties ON (sys.extended_properties.minor_id = syscolumns.colid
|
||||
AND sys.extended_properties.major_id = syscolumns.id)
|
||||
LEFT OUTER JOIN syscomments ON syscolumns.cdefault = syscomments.id
|
||||
WHERE syscolumns.id IN
|
||||
(SELECT id
|
||||
FROM sysobjects
|
||||
WHERE upper(xtype) IN('U',
|
||||
'V') )
|
||||
AND (systypes.name <> 'sysname')
|
||||
AND sysobjects.name='{0}'
|
||||
AND systypes.name<>'geometry'
|
||||
AND systypes.name<>'geography'
|
||||
ORDER BY syscolumns.colid";
|
||||
return sql;
|
||||
}
|
||||
}
|
||||
protected override string GetTableInfoListSql
|
||||
{
|
||||
get
|
||||
{
|
||||
return @"select
|
||||
trim(a.tabname) as name,
|
||||
trim(b.comments) as Description
|
||||
from systables a
|
||||
left join syscomments b on b.tabname = a.tabname
|
||||
where a.tabtype in ('T') and not (a.tabname like 'sys%') AND a.tabname <>'dual' ";
|
||||
}
|
||||
}
|
||||
protected override string GetViewInfoListSql
|
||||
{
|
||||
get
|
||||
{
|
||||
return @"select
|
||||
trim(a.tabname) as name,
|
||||
trim(b.comments) as Description
|
||||
from systables a
|
||||
left join syscomments b on b.tabname = a.tabname
|
||||
where a.tabtype in ('V') and not (a.tabname like 'sys%') AND a.tabname <>'dual' ";
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region DDL
|
||||
protected override string CreateDataBaseSql
|
||||
{
|
||||
get
|
||||
{
|
||||
return @"create database {0} ";
|
||||
}
|
||||
}
|
||||
protected override string AddPrimaryKeySql
|
||||
{
|
||||
get
|
||||
{
|
||||
return "ALTER TABLE {0} ADD CONSTRAINT {1} PRIMARY KEY({2})";
|
||||
}
|
||||
}
|
||||
protected override string AddColumnToTableSql
|
||||
{
|
||||
get
|
||||
{
|
||||
return "ALTER TABLE {0} ADD {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 @"USE master;BACKUP DATABASE {0} TO disk = '{1}'";
|
||||
}
|
||||
}
|
||||
protected override string CreateTableSql
|
||||
{
|
||||
get
|
||||
{
|
||||
return "CREATE TABLE {0}(\r\n{1})";
|
||||
}
|
||||
}
|
||||
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 "SELECT TOP {0} * INTO {1} FROM {2}";
|
||||
}
|
||||
}
|
||||
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 "exec sp_rename '{0}.{1}','{2}','column';";
|
||||
}
|
||||
}
|
||||
protected override string AddColumnRemarkSql
|
||||
{
|
||||
get
|
||||
{
|
||||
return "EXECUTE sp_addextendedproperty N'MS_Description', N'{2}', N'user', N'dbo', N'table', N'{1}', N'column', N'{0}'"; ;
|
||||
}
|
||||
}
|
||||
|
||||
protected override string DeleteColumnRemarkSql
|
||||
{
|
||||
get
|
||||
{
|
||||
return "EXEC sp_dropextendedproperty 'MS_Description','user',dbo,'table','{1}','column','{0}'";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected override string IsAnyColumnRemarkSql
|
||||
{
|
||||
get
|
||||
{
|
||||
return @"SELECT" +
|
||||
" A.name AS table_name," +
|
||||
" B.name AS column_name," +
|
||||
" C.value AS column_description" +
|
||||
" FROM sys.tables A" +
|
||||
" LEFT JOIN sys.extended_properties C ON C.major_id = A.object_id" +
|
||||
" LEFT JOIN sys.columns B ON B.object_id = A.object_id AND C.minor_id = B.column_id" +
|
||||
" INNER JOIN sys.schemas SC ON SC.schema_id = A.schema_id AND SC.name = 'dbo'" +
|
||||
" WHERE A.name = '{1}' and B.name = '{0}'";
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
protected override string AddTableRemarkSql
|
||||
{
|
||||
get
|
||||
{
|
||||
return "EXECUTE sp_addextendedproperty N'MS_Description', '{1}', N'user', N'dbo', N'table', N'{0}', NULL, NULL";
|
||||
}
|
||||
}
|
||||
|
||||
protected override string DeleteTableRemarkSql
|
||||
{
|
||||
get
|
||||
{
|
||||
return "EXEC sp_dropextendedproperty 'MS_Description','user',dbo,'table','{0}' ";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected override string IsAnyTableRemarkSql
|
||||
{
|
||||
get
|
||||
{
|
||||
return @"SELECT C.class_desc
|
||||
FROM sys.tables A
|
||||
LEFT JOIN sys.extended_properties C ON C.major_id = A.object_id
|
||||
INNER JOIN sys.schemas SC ON SC.schema_id=A.schema_id AND SC.name='dbo'
|
||||
WHERE A.name = '{0}' AND minor_id=0";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected override string RenameTableSql
|
||||
{
|
||||
get
|
||||
{
|
||||
return "EXEC sp_rename '{0}','{1}'";
|
||||
}
|
||||
}
|
||||
|
||||
protected override string CreateIndexSql
|
||||
{
|
||||
get
|
||||
{
|
||||
return "CREATE {3} NONCLUSTERED INDEX Index_{0}_{2} ON {0}({1})";
|
||||
}
|
||||
}
|
||||
protected override string AddDefaultValueSql
|
||||
{
|
||||
get
|
||||
{
|
||||
return "alter table {0} ADD DEFAULT '{2}' FOR {1}";
|
||||
}
|
||||
}
|
||||
protected override string IsAnyIndexSql
|
||||
{
|
||||
get
|
||||
{
|
||||
return "select count(*) from sys.indexes where name='{0}'";
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Check
|
||||
protected override string CheckSystemTablePermissionsSql
|
||||
{
|
||||
get
|
||||
{
|
||||
return "SELECT TOP 1 * FROM Systables";
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Scattered
|
||||
protected override string CreateTableNull
|
||||
{
|
||||
get
|
||||
{
|
||||
return "NULL";
|
||||
}
|
||||
}
|
||||
protected override string CreateTableNotNull
|
||||
{
|
||||
get
|
||||
{
|
||||
return "NOT NULL";
|
||||
}
|
||||
}
|
||||
protected override string CreateTablePirmaryKey
|
||||
{
|
||||
get
|
||||
{
|
||||
return "PRIMARY KEY";
|
||||
}
|
||||
}
|
||||
protected override string CreateTableIdentity
|
||||
{
|
||||
get
|
||||
{
|
||||
return "IDENTITY(1,1)";
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Methods
|
||||
public override List<DbColumnInfo> GetColumnInfosByTableName(string tableName, bool isCache = true)
|
||||
{
|
||||
string cacheKey = "DbMaintenanceProvider.GetColumnInfosByTableName." + this.SqlBuilder.GetNoTranslationColumnName(tableName).ToLower();
|
||||
cacheKey = GetCacheKey(cacheKey);
|
||||
if (!isCache)
|
||||
return GetColumnInfosByTableName(tableName);
|
||||
else
|
||||
return this.Context.Utilities.GetReflectionInoCacheInstance().GetOrCreate(cacheKey,
|
||||
() =>
|
||||
{
|
||||
return GetColumnInfosByTableName(tableName);
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
private List<DbColumnInfo> GetColumnInfosByTableName(string tableName)
|
||||
{
|
||||
string sql = "select * /* " + Guid.NewGuid() + " */ from " + SqlBuilder.GetTranslationTableName(tableName) + " WHERE 1=2 ";
|
||||
this.Context.Utilities.RemoveCache<List<DbColumnInfo>>("DbMaintenanceProvider.GetFieldComment." + tableName);
|
||||
this.Context.Utilities.RemoveCache<List<string>>("DbMaintenanceProvider.GetPrimaryKeyByTableNames." + this.SqlBuilder.GetNoTranslationColumnName(tableName).ToLower());
|
||||
var oldIsEnableLog = this.Context.Ado.IsEnableLogEvent;
|
||||
this.Context.Ado.IsEnableLogEvent = false;
|
||||
using (var reader = this.Context.Ado.GetDataReader(sql))
|
||||
{
|
||||
this.Context.Ado.IsEnableLogEvent = oldIsEnableLog;
|
||||
List<DbColumnInfo> result = new List<DbColumnInfo>();
|
||||
var schemaTable = reader.GetSchemaTable();
|
||||
int i = 0;
|
||||
foreach (System.Data.DataRow row in schemaTable.Rows)
|
||||
{
|
||||
DbColumnInfo column = new DbColumnInfo()
|
||||
{
|
||||
TableName = tableName,
|
||||
DataType = row["DataType"].ToString().Replace("System.", "").Trim(),
|
||||
IsNullable = (bool)row["AllowDBNull"],
|
||||
IsIdentity = (bool)row["IsAutoIncrement"],
|
||||
// ColumnDescription = GetFieldComment(tableName, row["ColumnName"].ToString()),
|
||||
DbColumnName = row["ColumnName"].ToString(),
|
||||
//DefaultValue = row["defaultValue"].ToString(),
|
||||
IsPrimarykey = i==0,//no support get pk
|
||||
Length = row["ColumnSize"].ObjToInt(),
|
||||
Scale = row["numericscale"].ObjToInt()
|
||||
};
|
||||
++i;
|
||||
result.Add(column);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
protected override string GetCreateTableSql(string tableName, List<DbColumnInfo> columns)
|
||||
{
|
||||
List<string> columnArray = new List<string>();
|
||||
Check.Exception(columns.IsNullOrEmpty(), "No columns found ");
|
||||
foreach (var item in columns)
|
||||
{
|
||||
string columnName = this.SqlBuilder.GetTranslationTableName(item.DbColumnName);
|
||||
string dataType = item.DataType;
|
||||
string dataSize = GetSize(item);
|
||||
string nullType = item.IsNullable ? this.CreateTableNull : CreateTableNotNull;
|
||||
if (item.IsIdentity&&item.IsPrimarykey)
|
||||
{
|
||||
dataSize = "";
|
||||
dataType = "serial primary key";
|
||||
}
|
||||
else if (item.IsIdentity)
|
||||
{
|
||||
dataSize = "";
|
||||
dataType = "serial";
|
||||
}
|
||||
else if (item.IsPrimarykey)
|
||||
{
|
||||
dataType = (dataType + dataSize + " primary key");
|
||||
dataSize = "";
|
||||
}
|
||||
//string identity = item.IsIdentity ? this.CreateTableIdentity : null;
|
||||
string addItem = string.Format(this.CreateTableColumn, columnName, dataType, dataSize, nullType, "", "");
|
||||
columnArray.Add(addItem);
|
||||
}
|
||||
string tableString = string.Format(this.CreateTableSql, this.SqlBuilder.GetTranslationTableName(tableName), string.Join(",\r\n", columnArray));
|
||||
return tableString;
|
||||
}
|
||||
|
||||
|
||||
public override bool AddDefaultValue(string tableName, string columnName, string defaultValue)
|
||||
{
|
||||
if (defaultValue == "''")
|
||||
{
|
||||
defaultValue = "";
|
||||
}
|
||||
var template = AddDefaultValueSql;
|
||||
if (defaultValue != null && defaultValue.ToLower() == "getdate()")
|
||||
{
|
||||
template = template.Replace("'{2}'", "{2}");
|
||||
}
|
||||
string sql = string.Format(template, tableName, columnName, defaultValue);
|
||||
this.Context.Ado.ExecuteCommand(sql);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///by current connection string
|
||||
/// </summary>
|
||||
/// <param name="databaseDirectory"></param>
|
||||
/// <returns></returns>
|
||||
public override bool CreateDatabase(string databaseName, string databaseDirectory = null)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
public override void AddDefaultValue(EntityInfo entityInfo)
|
||||
{
|
||||
|
||||
}
|
||||
public override bool CreateTable(string tableName, List<DbColumnInfo> columns, bool isCreatePrimaryKey = true)
|
||||
{
|
||||
tableName = this.SqlBuilder.GetTranslationTableName(tableName);
|
||||
foreach (var item in columns)
|
||||
{
|
||||
if (item.DataType == "decimal" && item.DecimalDigits == 0 && item.Length == 0)
|
||||
{
|
||||
item.DecimalDigits = 4;
|
||||
item.Length = 18;
|
||||
}
|
||||
}
|
||||
string sql = GetCreateTableSql(tableName, columns);
|
||||
this.Context.Ado.ExecuteCommand(sql);
|
||||
//if (isCreatePrimaryKey)
|
||||
//{
|
||||
// var pkColumns = columns.Where(it => it.IsPrimarykey).ToList();
|
||||
// if (pkColumns.Count > 1)
|
||||
// {
|
||||
// this.Context.DbMaintenance.AddPrimaryKeys(tableName, pkColumns.Select(it => it.DbColumnName).ToArray());
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// foreach (var item in pkColumns)
|
||||
// {
|
||||
// this.Context.DbMaintenance.AddPrimaryKey(tableName, item.DbColumnName);
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
return true;
|
||||
}
|
||||
//public override List<DbColumnInfo> GetColumnInfosByTableName(string tableName, bool isCache = true)
|
||||
//{
|
||||
// tableName = SqlBuilder.GetNoTranslationColumnName(tableName);
|
||||
// var result= base.GetColumnInfosByTableName(tableName, isCache);
|
||||
// return result;
|
||||
//}
|
||||
public override bool RenameColumn(string tableName, string oldColumnName, string newColumnName)
|
||||
{
|
||||
tableName = this.SqlBuilder.GetTranslationTableName(tableName);
|
||||
oldColumnName = this.SqlBuilder.GetTranslationColumnName(oldColumnName);
|
||||
newColumnName = this.SqlBuilder.GetNoTranslationColumnName(newColumnName);
|
||||
string sql = string.Format(this.RenameColumnSql, tableName, oldColumnName, newColumnName);
|
||||
this.Context.Ado.ExecuteCommand(sql);
|
||||
return true;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
330
Src/Asp.NetCore2/SqlSugar.OdbcCore/GBase/GBaseProvider.cs
Normal file
330
Src/Asp.NetCore2/SqlSugar.OdbcCore/GBase/GBaseProvider.cs
Normal file
@ -0,0 +1,330 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Xml.Linq;
|
||||
using System.Data.Odbc;
|
||||
using System.Text.RegularExpressions;
|
||||
namespace SqlSugar.Odbc
|
||||
{
|
||||
public class OdbcProvider : AdoProvider
|
||||
{
|
||||
public OdbcProvider() { }
|
||||
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<object> 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<object> _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<int> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Only Odbc
|
||||
/// </summary>
|
||||
/// <param name="transactionName"></param>
|
||||
public override void BeginTran(string transactionName)
|
||||
{
|
||||
CheckConnection();
|
||||
base.Transaction = ((OdbcConnection)this.Connection).BeginTransaction();
|
||||
}
|
||||
/// <summary>
|
||||
/// Only Odbc
|
||||
/// </summary>
|
||||
/// <param name="iso"></param>
|
||||
/// <param name="transactionName"></param>
|
||||
public override void BeginTran(IsolationLevel iso, string transactionName)
|
||||
{
|
||||
CheckConnection();
|
||||
base.Transaction = ((OdbcConnection)this.Connection).BeginTransaction(iso);
|
||||
}
|
||||
|
||||
public override IDataAdapter GetAdapter()
|
||||
{
|
||||
return new OdbcDataAdapter();
|
||||
}
|
||||
public override DbCommand GetCommand(string sql, SugarParameter[] parameters)
|
||||
{
|
||||
var helper = new OdbcInsertBuilder();
|
||||
helper.Context = this.Context;
|
||||
if (parameters != null)
|
||||
{
|
||||
foreach (var param in parameters.OrderByDescending(it => it.ParameterName.Length))
|
||||
{
|
||||
sql = sql.Replace(param.ParameterName, helper.FormatValue(param.Value) + "");
|
||||
}
|
||||
}
|
||||
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 (parameters.HasValue())
|
||||
//{
|
||||
// OdbcParameter[] ipars = GetSqlParameter(parameters);
|
||||
// sqlCommand.Parameters.AddRange(ipars);
|
||||
//}
|
||||
CheckConnection();
|
||||
return sqlCommand;
|
||||
}
|
||||
public override void SetCommandToAdapter(IDataAdapter dataAdapter, DbCommand command)
|
||||
{
|
||||
((OdbcDataAdapter)dataAdapter).SelectCommand = (OdbcCommand)command;
|
||||
}
|
||||
/// <summary>
|
||||
/// if mysql return MySqlParameter[] pars
|
||||
/// if sqlerver return SqlParameter[] pars ...
|
||||
/// </summary>
|
||||
/// <param name="parameters"></param>
|
||||
/// <returns></returns>
|
||||
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<IDataParameter>();
|
||||
this.OutputParameters.RemoveAll(it => it.ParameterName == sqlParameter.ParameterName);
|
||||
this.OutputParameters.Add(sqlParameter);
|
||||
}
|
||||
++index;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/// <summary>
|
||||
/// if mysql return MySqlParameter[] pars
|
||||
/// if sqlerver return SqlParameter[] pars ...
|
||||
/// </summary>
|
||||
/// <param name="parameters"></param>
|
||||
/// <returns></returns>
|
||||
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<IDataParameter>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,58 @@
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Text;
|
||||
|
||||
namespace SqlSugar.Odbc
|
||||
{
|
||||
public class OdbcQueryable<T>:QueryableProvider<T>
|
||||
{
|
||||
|
||||
}
|
||||
public class OdbcQueryable<T,T2> : QueryableProvider<T,T2>
|
||||
{
|
||||
|
||||
}
|
||||
public class OdbcQueryable<T, T2,T3> : QueryableProvider<T, T2,T3>
|
||||
{
|
||||
|
||||
}
|
||||
public class OdbcQueryable<T, T2,T3,T4> : QueryableProvider<T, T2,T3,T4>
|
||||
{
|
||||
|
||||
}
|
||||
public class OdbcQueryable<T, T2, T3, T4,T5> : QueryableProvider<T, T2, T3, T4,T5>
|
||||
{
|
||||
|
||||
}
|
||||
public class OdbcQueryable<T, T2, T3, T4, T5,T6> : QueryableProvider<T, T2, T3, T4, T5,T6>
|
||||
{
|
||||
|
||||
}
|
||||
public class OdbcQueryable<T, T2, T3, T4, T5, T6,T7> : QueryableProvider<T, T2, T3, T4, T5, T6,T7>
|
||||
{
|
||||
|
||||
}
|
||||
public class OdbcQueryable<T, T2, T3, T4, T5, T6, T7,T8> : QueryableProvider<T, T2, T3, T4, T5, T6, T7,T8>
|
||||
{
|
||||
|
||||
}
|
||||
public class OdbcQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9> : QueryableProvider<T, T2, T3, T4, T5, T6, T7, T8, T9>
|
||||
{
|
||||
|
||||
}
|
||||
public class OdbcQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10> : QueryableProvider<T, T2, T3, T4, T5, T6, T7, T8, T9, T10>
|
||||
{
|
||||
|
||||
}
|
||||
public class OdbcQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> : QueryableProvider<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>
|
||||
{
|
||||
|
||||
}
|
||||
public class OdbcQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> : QueryableProvider<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>
|
||||
{
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,154 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SqlSugar.Odbc
|
||||
{
|
||||
public class OdbcBlukCopy
|
||||
{
|
||||
internal List<IGrouping<int, DbColumnInfo>> 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<int> 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<DataColumn>().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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,64 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SqlSugar.Odbc
|
||||
{
|
||||
public class OdbcBuilder : SqlBuilderProvider
|
||||
{
|
||||
public override string SqlTranslationLeft { get { return ""; } }
|
||||
public override string SqlTranslationRight { get { return ""; } }
|
||||
public override string GetNoTranslationColumnName(string name)
|
||||
{
|
||||
return name;
|
||||
}
|
||||
public override string SqlDateNow
|
||||
{
|
||||
get
|
||||
{
|
||||
return "sysdate";
|
||||
}
|
||||
}
|
||||
public override string FullSqlDateNow
|
||||
{
|
||||
get
|
||||
{
|
||||
return "select sysdate from dual";
|
||||
}
|
||||
}
|
||||
public override string GetTranslationTableName(string name)
|
||||
{
|
||||
Check.ArgumentNullException(name, string.Format(ErrorMessage.ObjNotExist, "Table Name"));
|
||||
if (!name.Contains("<>f__AnonymousType") && name.IsContainsIn("(", ")") && name != "Dictionary`2")
|
||||
{
|
||||
return name;
|
||||
}
|
||||
if (Context.MappingTables == null)
|
||||
{
|
||||
return name;
|
||||
}
|
||||
var context = this.Context;
|
||||
var mappingInfo = context
|
||||
.MappingTables
|
||||
.FirstOrDefault(it => it.EntityName.Equals(name, StringComparison.CurrentCultureIgnoreCase));
|
||||
name = (mappingInfo == null ? name : mappingInfo.DbTableName);
|
||||
if (name.IsContainsIn("(", ")", SqlTranslationLeft))
|
||||
{
|
||||
return name;
|
||||
}
|
||||
if (name.Contains("."))
|
||||
{
|
||||
return string.Join(".", name.Split('.').Select(it => SqlTranslationLeft + it + SqlTranslationRight));
|
||||
}
|
||||
else
|
||||
{
|
||||
return SqlTranslationLeft + name + SqlTranslationRight;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SqlSugar.Odbc
|
||||
{
|
||||
public class OdbcDeleteBuilder: DeleteBuilder
|
||||
{
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,114 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SqlSugar.Odbc
|
||||
{
|
||||
public partial class OdbcExpressionContext : ExpressionContext, ILambdaExpressions
|
||||
{
|
||||
public SqlSugarProvider Context { get; set; }
|
||||
public OdbcExpressionContext()
|
||||
{
|
||||
base.DbMehtods = new OdbcMethod();
|
||||
}
|
||||
public override string SqlTranslationLeft { get { return ""; } }
|
||||
public override string SqlTranslationRight { get { return ""; } }
|
||||
public override bool IsTranslationText(string name)
|
||||
{
|
||||
var result = name.IsContainsIn( UtilConstants.Space,"(",")");
|
||||
return result;
|
||||
}
|
||||
public override string GetLimit() { return ""; }
|
||||
}
|
||||
public partial class OdbcMethod : DefaultDbMethod, IDbMethods
|
||||
{
|
||||
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 GetRandom()
|
||||
{
|
||||
return " SYS_GUID() ";
|
||||
}
|
||||
public override string GetForXmlPath()
|
||||
{
|
||||
return " FOR XML PATH('')),1,len(N','),'') ";
|
||||
}
|
||||
public override string GetStringJoinSelector(string result, string separator)
|
||||
{
|
||||
return $"stuff((SELECT cast(N'{separator}' as nvarchar(max)) + cast({result} as nvarchar(max))";
|
||||
}
|
||||
public override string DateValue(MethodCallExpressionModel model)
|
||||
{
|
||||
var parameter = model.Args[0];
|
||||
var parameter2 = model.Args[1];
|
||||
if (parameter.MemberName != null && parameter.MemberName is DateTime)
|
||||
{
|
||||
return string.Format(" datepart({0},'{1}') ", parameter2.MemberValue, parameter.MemberName);
|
||||
}
|
||||
else
|
||||
{
|
||||
return string.Format(" datepart({0},{1}) ", parameter2.MemberValue, parameter.MemberName);
|
||||
}
|
||||
}
|
||||
public override string GetDate()
|
||||
{
|
||||
return " sysdate ";
|
||||
}
|
||||
|
||||
public override string HasValue(MethodCallExpressionModel model)
|
||||
{
|
||||
if (model.Args[0].Type == UtilConstants.GuidType)
|
||||
{
|
||||
var parameter = model.Args[0];
|
||||
return string.Format("( {0} IS NOT NULL )", parameter.MemberName);
|
||||
}
|
||||
else
|
||||
{
|
||||
var parameter = model.Args[0];
|
||||
return string.Format("( {0}<>'' AND {0} IS NOT NULL )", parameter.MemberName);
|
||||
}
|
||||
}
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
using Microsoft.Data.SqlClient;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SqlSugar.Odbc
|
||||
{
|
||||
|
||||
public class OdbcFastBuilder:FastBuilder,IFastBuilder
|
||||
{
|
||||
public override bool IsActionUpdateColumns { get; set; } = true;
|
||||
public override DbFastestProperties DbFastestProperties { get; set; } = new DbFastestProperties() {
|
||||
HasOffsetTime=true
|
||||
};
|
||||
public async Task<int> ExecuteBulkCopyAsync(DataTable dt)
|
||||
{
|
||||
|
||||
SqlBulkCopy bulkCopy = GetBulkCopyInstance();
|
||||
bulkCopy.DestinationTableName = dt.TableName;
|
||||
try
|
||||
{
|
||||
await bulkCopy.WriteToServerAsync(dt);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
CloseDb();
|
||||
throw ex;
|
||||
}
|
||||
CloseDb();
|
||||
return dt.Rows.Count;
|
||||
}
|
||||
public 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;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,164 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SqlSugar.Odbc
|
||||
{
|
||||
public class OdbcInsertBuilder:InsertBuilder
|
||||
{
|
||||
public override string SqlTemplateBatch
|
||||
{
|
||||
get
|
||||
{
|
||||
return "INSERT into {0} ({1})";
|
||||
}
|
||||
}
|
||||
public override string SqlTemplate
|
||||
{
|
||||
get
|
||||
{
|
||||
if (IsReturnIdentity)
|
||||
{
|
||||
return @"INSERT INTO {0}
|
||||
({1})
|
||||
VALUES
|
||||
({2})"+UtilConstants.ReplaceCommaKey.Replace("{","").Replace("}", "") + " SELECT dbinfo('sqlca.sqlerrd1') FROM dual";
|
||||
}
|
||||
else
|
||||
{
|
||||
return @"INSERT INTO {0}
|
||||
({1})
|
||||
VALUES
|
||||
({2}) "+UtilConstants.ReplaceCommaKey.Replace("{", "").Replace("}", "") + "SELECT dbinfo('sqlca.sqlerrd1') FROM dual";
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
public override string GetTableNameString
|
||||
{
|
||||
get
|
||||
{
|
||||
var result = Builder.GetTranslationTableName(EntityInfo.EntityName);
|
||||
result += UtilConstants.Space;
|
||||
if (this.TableWithString.HasValue())
|
||||
{
|
||||
result += TableWithString + UtilConstants.Space;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
public override string ToSqlString()
|
||||
{
|
||||
if (IsNoInsertNull)
|
||||
{
|
||||
DbColumnInfoList = DbColumnInfoList.Where(it => it.Value != null).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)
|
||||
{
|
||||
string columnParametersString = string.Join(",", this.DbColumnInfoList.Select(it => Builder.SqlParameterKeyWord + it.DbColumnName));
|
||||
return string.Format(SqlTemplate, GetTableNameString, columnsString, columnParametersString);
|
||||
}
|
||||
else
|
||||
{
|
||||
StringBuilder batchInsetrSql = new StringBuilder();
|
||||
int pageSize = groupList.Count;
|
||||
int pageIndex = 1;
|
||||
int totalRecord = groupList.Count;
|
||||
int pageCount = (totalRecord + pageSize - 1) / pageSize;
|
||||
while (pageCount >= pageIndex)
|
||||
{
|
||||
batchInsetrSql.AppendFormat(SqlTemplateBatch, GetTableNameString, columnsString);
|
||||
batchInsetrSql.AppendFormat("SELECT * FROM (");
|
||||
int i = 0;
|
||||
foreach (var columns in groupList.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList())
|
||||
{
|
||||
var isFirst = i == 0;
|
||||
if (!isFirst)
|
||||
{
|
||||
batchInsetrSql.Append(SqlTemplateBatchUnion);
|
||||
}
|
||||
batchInsetrSql.Append("\r\n SELECT " + string.Join(",", columns.Select(it => string.Format(SqlTemplateBatchSelect, FormatValue(it.Value), Builder.GetTranslationColumnName(it.DbColumnName))))+" from dual");
|
||||
++i;
|
||||
}
|
||||
pageIndex++;
|
||||
batchInsetrSql.Append(") temp1\r\n;\r\n");
|
||||
}
|
||||
var result = batchInsetrSql.ToString();
|
||||
//if (this.Context.CurrentConnectionConfig.DbType == DbType.Odbc)
|
||||
//{
|
||||
// result += "";
|
||||
//}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
public override object FormatValue(object value)
|
||||
{
|
||||
var n = "";
|
||||
if (value == null)
|
||||
{
|
||||
return "NULL";
|
||||
}
|
||||
else
|
||||
{
|
||||
var type = UtilMethods.GetUnderType(value.GetType());
|
||||
if (type == UtilConstants.DateType)
|
||||
{
|
||||
return GetDateTimeString(value);
|
||||
}
|
||||
else if (value is DateTimeOffset)
|
||||
{
|
||||
return GetDateTimeOffsetString(value);
|
||||
}
|
||||
else if (type == UtilConstants.ByteArrayType)
|
||||
{
|
||||
string bytesString = "0x" + BitConverter.ToString((byte[])value).Replace("-", "");
|
||||
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
|
||||
{
|
||||
return n + "'" + value + "'";
|
||||
}
|
||||
}
|
||||
}
|
||||
private object GetDateTimeOffsetString(object value)
|
||||
{
|
||||
var date = UtilMethods.ConvertFromDateTimeOffset((DateTimeOffset)value);
|
||||
if (date < UtilMethods.GetMinDate(this.Context.CurrentConnectionConfig))
|
||||
{
|
||||
date = UtilMethods.GetMinDate(this.Context.CurrentConnectionConfig);
|
||||
}
|
||||
return "'" + date.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'";
|
||||
}
|
||||
|
||||
private object GetDateTimeString(object value)
|
||||
{
|
||||
var date = value.ObjToDate();
|
||||
if (date < UtilMethods.GetMinDate(this.Context.CurrentConnectionConfig))
|
||||
{
|
||||
date = UtilMethods.GetMinDate(this.Context.CurrentConnectionConfig);
|
||||
}
|
||||
return "'" + date.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'";
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,160 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SqlSugar.Odbc
|
||||
{
|
||||
public class OdbcQueryBuilder: QueryBuilder
|
||||
{
|
||||
#region Sql Template
|
||||
public override string PageTempalte
|
||||
{
|
||||
get
|
||||
{
|
||||
/*
|
||||
SELECT * FROM TABLE WHERE CONDITION ORDER BY ID DESC LIMIT 0,10
|
||||
*/
|
||||
var template = "SELECT {0} FROM {1} {2} {3} {4} LIMIT {5},{6}";
|
||||
return template;
|
||||
}
|
||||
}
|
||||
public override string DefaultOrderByTemplate
|
||||
{
|
||||
get
|
||||
{
|
||||
return "ORDER BY SysDate ";
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Common Methods
|
||||
public override bool IsComplexModel(string sql)
|
||||
{
|
||||
return Regex.IsMatch(sql, @"AS \`\w+\.\w+\`") || Regex.IsMatch(sql, @"AS \`\w+\.\w+\.\w+\`");
|
||||
}
|
||||
public override string ToSqlString()
|
||||
{
|
||||
base.AppendFilter();
|
||||
string oldOrderValue = this.OrderByValue;
|
||||
string result = null;
|
||||
sql = new StringBuilder();
|
||||
sql.AppendFormat(SqlTemplate, GetSelectValue, GetTableNameString, GetWhereValueString, GetGroupByString + HavingInfos, (Skip != null || Take != null) ? null : GetOrderByString);
|
||||
if (IsCount) { return sql.ToString(); }
|
||||
if (Skip != null && Take == null)
|
||||
{
|
||||
if (this.OrderByValue == "ORDER BY ") this.OrderByValue += GetSelectValue.Split(',')[0];
|
||||
result = string.Format(PageTempalte, GetSelectValue, GetTableNameString, GetWhereValueString, GetGroupByString + HavingInfos, (Skip != null || Take != null) ? null : GetOrderByString, Skip.ObjToInt(), long.MaxValue);
|
||||
}
|
||||
else if (Skip == null && Take != null)
|
||||
{
|
||||
if (this.OrderByValue == "ORDER BY ") this.OrderByValue += GetSelectValue.Split(',')[0];
|
||||
result = string.Format(PageTempalte, GetSelectValue, GetTableNameString, GetWhereValueString, GetGroupByString + HavingInfos, GetOrderByString, 0, Take.ObjToInt());
|
||||
}
|
||||
else if (Skip != null && Take != null)
|
||||
{
|
||||
if (Skip == 0 && Take == 1 && this.OrderByValue == "ORDER BY SysDate ")
|
||||
{
|
||||
this.OrderByValue = null;
|
||||
}
|
||||
if (this.OrderByValue == "ORDER BY ") this.OrderByValue += GetSelectValue.Split(',')[0];
|
||||
result = string.Format(PageTempalte, GetSelectValue, GetTableNameString, GetWhereValueString, GetGroupByString + HavingInfos, GetOrderByString, Skip.ObjToInt() > 0 ? Skip.ObjToInt() : 0, Take);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = sql.ToString();
|
||||
}
|
||||
this.OrderByValue = oldOrderValue;
|
||||
result = GetSqlQuerySql(result);
|
||||
if (result.IndexOf("-- No table") > 0)
|
||||
{
|
||||
return "-- No table";
|
||||
}
|
||||
if (TranLock != null)
|
||||
{
|
||||
result = result + TranLock;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
private string ToCountSqlString()
|
||||
{
|
||||
//base.AppendFilter();
|
||||
string oldOrderValue = this.OrderByValue;
|
||||
string result = null;
|
||||
sql = new StringBuilder();
|
||||
sql.AppendFormat(SqlTemplate, "Count(*)", GetTableNameString, GetWhereValueString, GetGroupByString + HavingInfos, (Skip != null || Take != null) ? null : GetOrderByString);
|
||||
if (IsCount)
|
||||
{
|
||||
if (sql.ToString().Contains("-- No table"))
|
||||
{
|
||||
return "-- No table";
|
||||
}
|
||||
return sql.ToString();
|
||||
}
|
||||
if (Skip != null && Take == null)
|
||||
{
|
||||
if (this.OrderByValue == "ORDER BY ") this.OrderByValue += GetSelectValue.Split(',')[0];
|
||||
result = string.Format(PageTempalte, GetSelectValue, GetTableNameString, GetWhereValueString, GetGroupByString + HavingInfos, (Skip != null || Take != null) ? null : GetOrderByString, Skip.ObjToInt(), long.MaxValue);
|
||||
}
|
||||
else if (Skip == null && Take != null)
|
||||
{
|
||||
if (this.OrderByValue == "ORDER BY ") this.OrderByValue += GetSelectValue.Split(',')[0];
|
||||
result = string.Format(PageTempalte, GetSelectValue, GetTableNameString, GetWhereValueString, GetGroupByString + HavingInfos, GetOrderByString, 0, Take.ObjToInt());
|
||||
}
|
||||
else if (Skip != null && Take != null)
|
||||
{
|
||||
if (this.OrderByValue == "ORDER BY ") this.OrderByValue += GetSelectValue.Split(',')[0];
|
||||
result = string.Format(PageTempalte, GetSelectValue, GetTableNameString, GetWhereValueString, GetGroupByString + HavingInfos, GetOrderByString, Skip.ObjToInt() > 0 ? Skip.ObjToInt() : 0, Take);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = sql.ToString();
|
||||
}
|
||||
this.OrderByValue = oldOrderValue;
|
||||
return result;
|
||||
}
|
||||
public override string ToCountSql(string sql)
|
||||
{
|
||||
if (this.GroupByValue.HasValue() || this.IsDistinct)
|
||||
{
|
||||
return base.ToCountSql(sql);
|
||||
}
|
||||
else
|
||||
{
|
||||
return ToCountSqlString();
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Get SQL Partial
|
||||
public override string GetSelectValue
|
||||
{
|
||||
get
|
||||
{
|
||||
string result = string.Empty;
|
||||
if (this.SelectValue == null || this.SelectValue is string)
|
||||
{
|
||||
result = GetSelectValueByString();
|
||||
}
|
||||
else
|
||||
{
|
||||
result = GetSelectValueByExpression();
|
||||
}
|
||||
if (this.SelectType == ResolveExpressType.SelectMultiple)
|
||||
{
|
||||
this.SelectCacheKey = this.SelectCacheKey + string.Join("-", this.JoinQueryInfos.Select(it => it.TableName));
|
||||
}
|
||||
if (IsDistinct)
|
||||
{
|
||||
result = " DISTINCT " + result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
@ -0,0 +1,113 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SqlSugar.Odbc
|
||||
{
|
||||
public class OdbcUpdateBuilder : UpdateBuilder
|
||||
{
|
||||
protected override string TomultipleSqlString(List<IGrouping<int, DbColumnInfo>> groupList)
|
||||
{
|
||||
if (groupList == null || groupList.Count == 0)
|
||||
{
|
||||
return "select 0 from DUAL";
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int i = 0;
|
||||
sb.AppendLine(string.Join(UtilConstants.ReplaceCommaKey.Replace("{", "").Replace("}", ""), groupList.Select(t =>
|
||||
{
|
||||
var updateTable = string.Format("UPDATE {0} SET ", base.GetTableNameStringNoWith);
|
||||
var setValues = string.Join(",", t.Where(s => !s.IsPrimarykey).Select(m => GetOracleUpdateColums(i, m, false)).ToArray());
|
||||
var pkList = t.Where(s => s.IsPrimarykey).ToList();
|
||||
List<string> whereList = new List<string>();
|
||||
foreach (var item in pkList)
|
||||
{
|
||||
var isFirst = pkList.First() == item;
|
||||
var whereString = "";
|
||||
whereString += GetOracleUpdateColums(i, item, true);
|
||||
whereList.Add(whereString);
|
||||
}
|
||||
i++;
|
||||
return string.Format("{0} {1} WHERE {2} ", updateTable, setValues, string.Join(" AND", whereList));
|
||||
}).ToArray()));
|
||||
return sb.ToString();
|
||||
}
|
||||
private object GetValue(DbColumnInfo it)
|
||||
{
|
||||
return FormatValue(it.Value);
|
||||
}
|
||||
private string GetOracleUpdateColums(int i, DbColumnInfo m, bool iswhere)
|
||||
{
|
||||
return string.Format("{0}={1}", m.DbColumnName, FormatValue(i, m.DbColumnName, m.Value, iswhere));
|
||||
}
|
||||
public object FormatValue(int i, string name, object value, bool iswhere)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
return "NULL";
|
||||
}
|
||||
else
|
||||
{
|
||||
var type = UtilMethods.GetUnderType(value.GetType());
|
||||
if (type == UtilConstants.DateType && iswhere == false)
|
||||
{
|
||||
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 "'" + date.ToString("yyyy-MM-dd HH:mm:ss") + "'";
|
||||
}
|
||||
else
|
||||
{
|
||||
return "'" + date.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'";
|
||||
}
|
||||
}
|
||||
else if (type == UtilConstants.DateType && iswhere)
|
||||
{
|
||||
var parameterName = this.Builder.SqlParameterKeyWord + name + i;
|
||||
this.Parameters.Add(new SugarParameter(parameterName, value));
|
||||
return parameterName;
|
||||
}
|
||||
else if (type.IsEnum())
|
||||
{
|
||||
if (this.Context.CurrentConnectionConfig.MoreSettings?.TableEnumIsString == true)
|
||||
{
|
||||
return value.ToSqlValue();
|
||||
}
|
||||
else
|
||||
{
|
||||
return Convert.ToInt64(value);
|
||||
}
|
||||
}
|
||||
else if (type == UtilConstants.ByteArrayType)
|
||||
{
|
||||
var parameterName = this.Builder.SqlParameterKeyWord + name + i;
|
||||
this.Parameters.Add(new SugarParameter(parameterName, value));
|
||||
return parameterName;
|
||||
}
|
||||
else if (value is int || value is long || value is short || value is short || value is byte)
|
||||
{
|
||||
return value;
|
||||
}
|
||||
else if (value is bool)
|
||||
{
|
||||
return value.ObjToString().ToLower();
|
||||
}
|
||||
else if (type == UtilConstants.StringType || type == UtilConstants.ObjType)
|
||||
{
|
||||
return "'" + value.ToString().ToSqlFilter() + "'";
|
||||
}
|
||||
else
|
||||
{
|
||||
return "'" + value.ToString() + "'";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
16
Src/Asp.NetCore2/SqlSugar.OdbcCore/SqlSugar.OdbcCore.csproj
Normal file
16
Src/Asp.NetCore2/SqlSugar.OdbcCore/SqlSugar.OdbcCore.csproj
Normal file
@ -0,0 +1,16 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.1</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="System.Data.Odbc" Version="4.6.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\SqlSugar\SqlSugar.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
64
Src/Asp.NetCore2/SqlSugar.OdbcCore/Tools/ErrorMessage.cs
Normal file
64
Src/Asp.NetCore2/SqlSugar.OdbcCore/Tools/ErrorMessage.cs
Normal file
@ -0,0 +1,64 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
namespace SqlSugar.Odbc
|
||||
{
|
||||
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<string, string>, or contact the author!!",
|
||||
"暂时不支持该类型的Dictionary 你可以试试 Dictionary<string ,string>或者联系作者!!");
|
||||
}
|
||||
}
|
||||
|
||||
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<string> formatArgs = new List<string>() { enMessage, cnMessage };
|
||||
formatArgs.AddRange(args);
|
||||
return string.Format(@"中文提示 : {1}
|
||||
English Message : {0}", formatArgs.ToArray());
|
||||
}
|
||||
else if (SugarLanguageType == LanguageType.English)
|
||||
{
|
||||
return enMessage;
|
||||
}
|
||||
else
|
||||
{
|
||||
return cnMessage;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
70
Src/Asp.NetCore2/SqlSugar.OdbcCore/Tools/FileHelper.cs
Normal file
70
Src/Asp.NetCore2/SqlSugar.OdbcCore/Tools/FileHelper.cs
Normal file
@ -0,0 +1,70 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace SqlSugar.Odbc
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
73
Src/Asp.NetCore2/SqlSugar.OdbcCore/Tools/UtilConstants.cs
Normal file
73
Src/Asp.NetCore2/SqlSugar.OdbcCore/Tools/UtilConstants.cs
Normal file
@ -0,0 +1,73 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Dynamic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
namespace SqlSugar.Odbc
|
||||
{
|
||||
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";
|
||||
internal const string ReplaceKey = "{662E689B-17A1-4D06-9D27-F29EAB8BC3D6}";
|
||||
internal const string ReplaceCommaKey = "{112A689B-17A1-4A06-9D27-A39EAB8BC3D5}";
|
||||
|
||||
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 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<int, int>);
|
||||
internal static Type DicIS = typeof(KeyValuePair<int, string>);
|
||||
internal static Type DicSi = typeof(KeyValuePair<string, int>);
|
||||
internal static Type DicSS = typeof(KeyValuePair<string, string>);
|
||||
internal static Type DicOO = typeof(KeyValuePair<object, object>);
|
||||
internal static Type DicSo = typeof(KeyValuePair<string, object>);
|
||||
internal static Type DicArraySS = typeof(Dictionary<string, string>);
|
||||
internal static Type DicArraySO = typeof(Dictionary<string, object>);
|
||||
|
||||
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 string[] DateTypeStringList = new string[]
|
||||
{
|
||||
"Year",
|
||||
"Month",
|
||||
"Day",
|
||||
"Hour",
|
||||
"Second" ,
|
||||
"Minute",
|
||||
"Millisecond",
|
||||
"Date"
|
||||
};
|
||||
}
|
||||
}
|
142
Src/Asp.NetCore2/SqlSugar.OdbcCore/Tools/UtilExtensions.cs
Normal file
142
Src/Asp.NetCore2/SqlSugar.OdbcCore/Tools/UtilExtensions.cs
Normal file
@ -0,0 +1,142 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
namespace SqlSugar.Odbc
|
||||
{
|
||||
/// <summary>
|
||||
///Common Extensions for external users
|
||||
/// </summary>
|
||||
public static class UtilExtensions
|
||||
{
|
||||
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 ToLower(this string value, bool isLower)
|
||||
{
|
||||
if (isLower)
|
||||
{
|
||||
return value.ObjToString().ToLower();
|
||||
}
|
||||
return value.ObjToString();
|
||||
}
|
||||
public static int ObjToInt(this object thisValue)
|
||||
{
|
||||
int reval = 0;
|
||||
if (thisValue == null) return 0;
|
||||
if (thisValue is Enum)
|
||||
{
|
||||
return (int)thisValue;
|
||||
}
|
||||
if (thisValue != null && thisValue != DBNull.Value && int.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 string ObjToString(this object thisValue)
|
||||
{
|
||||
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)
|
||||
{
|
||||
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)
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
507
Src/Asp.NetCore2/SqlSugar.OdbcCore/Tools/UtilMethods.cs
Normal file
507
Src/Asp.NetCore2/SqlSugar.OdbcCore/Tools/UtilMethods.cs
Normal file
@ -0,0 +1,507 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Data;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
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.Odbc
|
||||
{
|
||||
public class UtilMethods
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
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();
|
||||
|
||||
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.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 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;
|
||||
}
|
||||
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<StackTraceInfoItem>();
|
||||
info.SugarStackTraceList = new List<StackTraceInfoItem>();
|
||||
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 T To<T>(object value)
|
||||
{
|
||||
return (T)To(value, typeof(T));
|
||||
}
|
||||
internal static Type GetUnderType(Type oldType)
|
||||
{
|
||||
Type type = Nullable.GetUnderlyingType(oldType);
|
||||
return type == null ? oldType : type;
|
||||
}
|
||||
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>(T returnObj) where T : new()
|
||||
//{
|
||||
// if (returnObj.IsNullOrEmpty())
|
||||
// {
|
||||
// returnObj = new T();
|
||||
// }
|
||||
// return returnObj;
|
||||
//}
|
||||
public static object ChangeType2(object value, Type type)
|
||||
{
|
||||
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 (!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;
|
||||
return Convert.ChangeType(value, type);
|
||||
}
|
||||
|
||||
internal static T ChangeType<T>(T obj, Type type)
|
||||
{
|
||||
return (T)Convert.ChangeType(obj, type);
|
||||
}
|
||||
|
||||
internal static T ChangeType<T>(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 string GetPackTable(string sql, string shortName)
|
||||
{
|
||||
return string.Format(" ({0}) {1} ", sql, shortName);
|
||||
}
|
||||
|
||||
public static Func<string, object> 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, @"\(.+\)"))
|
||||
{
|
||||
dbTypeName = Regex.Replace(dbTypeName, @"\(.+\)", "");
|
||||
}
|
||||
dbTypeName = dbTypeName.Trim();
|
||||
return dbTypeName;
|
||||
}
|
||||
|
||||
internal static T GetOldValue<T>(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 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 (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 (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 void DataInoveByExpresson<Type>(Type[] datas, MethodCallExpression callExpresion)
|
||||
{
|
||||
var methodInfo = callExpresion.Method;
|
||||
foreach (var item in datas)
|
||||
{
|
||||
if (callExpresion.Arguments.Count == 0)
|
||||
{
|
||||
methodInfo.Invoke(item, null);
|
||||
}
|
||||
else
|
||||
{
|
||||
List<object> methodParameters = new List<object>();
|
||||
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<string, T> EnumToDictionary<T>()
|
||||
{
|
||||
Dictionary<string, T> dic = new Dictionary<string, T>();
|
||||
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 object ConvertDataByTypeName(string ctypename,string value)
|
||||
//{
|
||||
// var item = new ConditionalModel() {
|
||||
// CSharpTypeName = ctypename,
|
||||
// FieldValue = value
|
||||
// };
|
||||
// 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.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))
|
||||
// {
|
||||
// return UtilMethods.GetDateTimeOffsetByDateTime(Convert.ToDateTime(item.FieldValue));
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// return item.FieldValue;
|
||||
// }
|
||||
//}
|
||||
}
|
||||
}
|
172
Src/Asp.NetCore2/SqlSugar.OdbcCore/Tools/ValidateExtensions.cs
Normal file
172
Src/Asp.NetCore2/SqlSugar.OdbcCore/Tools/ValidateExtensions.cs
Normal file
@ -0,0 +1,172 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
namespace SqlSugar.Odbc
|
||||
{
|
||||
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<T>(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<object> 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<object> thisValue)
|
||||
{
|
||||
if (thisValue == null || thisValue.Count() == 0) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool IsValuable(this IEnumerable<KeyValuePair<string,string>> 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+$");
|
||||
}
|
||||
|
||||
/// <returns></returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
@ -56,6 +56,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
|
||||
.editorconfig = .editorconfig
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OdbcTest", "OdbcTest\OdbcTest.csproj", "{27CDB82D-51EF-447B-87F1-EEF08C629F9E}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SqlSugar.OdbcCore", "SqlSugar.OdbcCore\SqlSugar.OdbcCore.csproj", "{0320D162-4E7F-4AA1-844B-2FDF77EEC145}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@ -342,6 +346,30 @@ Global
|
||||
{73861B80-AC53-441D-A178-C8F3C1FF0FB3}.Release|ARM32.Build.0 = Release|Any CPU
|
||||
{73861B80-AC53-441D-A178-C8F3C1FF0FB3}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{73861B80-AC53-441D-A178-C8F3C1FF0FB3}.Release|x86.Build.0 = Release|Any CPU
|
||||
{27CDB82D-51EF-447B-87F1-EEF08C629F9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{27CDB82D-51EF-447B-87F1-EEF08C629F9E}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{27CDB82D-51EF-447B-87F1-EEF08C629F9E}.Debug|ARM32.ActiveCfg = Debug|Any CPU
|
||||
{27CDB82D-51EF-447B-87F1-EEF08C629F9E}.Debug|ARM32.Build.0 = Debug|Any CPU
|
||||
{27CDB82D-51EF-447B-87F1-EEF08C629F9E}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{27CDB82D-51EF-447B-87F1-EEF08C629F9E}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{27CDB82D-51EF-447B-87F1-EEF08C629F9E}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{27CDB82D-51EF-447B-87F1-EEF08C629F9E}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{27CDB82D-51EF-447B-87F1-EEF08C629F9E}.Release|ARM32.ActiveCfg = Release|Any CPU
|
||||
{27CDB82D-51EF-447B-87F1-EEF08C629F9E}.Release|ARM32.Build.0 = Release|Any CPU
|
||||
{27CDB82D-51EF-447B-87F1-EEF08C629F9E}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{27CDB82D-51EF-447B-87F1-EEF08C629F9E}.Release|x86.Build.0 = Release|Any CPU
|
||||
{0320D162-4E7F-4AA1-844B-2FDF77EEC145}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{0320D162-4E7F-4AA1-844B-2FDF77EEC145}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{0320D162-4E7F-4AA1-844B-2FDF77EEC145}.Debug|ARM32.ActiveCfg = Debug|Any CPU
|
||||
{0320D162-4E7F-4AA1-844B-2FDF77EEC145}.Debug|ARM32.Build.0 = Debug|Any CPU
|
||||
{0320D162-4E7F-4AA1-844B-2FDF77EEC145}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{0320D162-4E7F-4AA1-844B-2FDF77EEC145}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{0320D162-4E7F-4AA1-844B-2FDF77EEC145}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{0320D162-4E7F-4AA1-844B-2FDF77EEC145}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{0320D162-4E7F-4AA1-844B-2FDF77EEC145}.Release|ARM32.ActiveCfg = Release|Any CPU
|
||||
{0320D162-4E7F-4AA1-844B-2FDF77EEC145}.Release|ARM32.Build.0 = Release|Any CPU
|
||||
{0320D162-4E7F-4AA1-844B-2FDF77EEC145}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{0320D162-4E7F-4AA1-844B-2FDF77EEC145}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@ -351,6 +379,7 @@ Global
|
||||
{DD0C850D-86E5-4FFF-BFF3-8797EB448B47} = {88992AAF-146B-4253-9AD7-493E8F415B57}
|
||||
{8C38F3D1-6D72-483C-9DBD-3111D6F5898D} = {88992AAF-146B-4253-9AD7-493E8F415B57}
|
||||
{73861B80-AC53-441D-A178-C8F3C1FF0FB3} = {88992AAF-146B-4253-9AD7-493E8F415B57}
|
||||
{0320D162-4E7F-4AA1-844B-2FDF77EEC145} = {88992AAF-146B-4253-9AD7-493E8F415B57}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {230A85B9-54F1-41B1-B1DA-80086581B2B4}
|
||||
|
Loading…
Reference in New Issue
Block a user