【测试】三大数据库,添加所有类型数据null/非空,后查询正常

This commit is contained in:
28810 2018-12-26 19:54:41 +08:00
parent 9c3e844e97
commit 070254127d
29 changed files with 593 additions and 121 deletions

View File

@ -3,6 +3,7 @@ using Newtonsoft.Json;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
using Xunit; using Xunit;
namespace FreeSql.Tests.MySql { namespace FreeSql.Tests.MySql {
@ -83,6 +84,82 @@ namespace FreeSql.Tests.MySql {
sql = g.mysql.CodeFirst.GetComparisonDDLStatements<Tb_alltype>(); sql = g.mysql.CodeFirst.GetComparisonDDLStatements<Tb_alltype>();
} }
IInsert<TableAllType> insert => g.mysql.Insert<TableAllType>();
ISelect<TableAllType> select => g.mysql.Select<TableAllType>();
[Fact]
public void CurdAllField() {
var item = new TableAllType { };
item.Id = (int)insert.AppendData(item).ExecuteIdentity();
var newitem = select.Where(a => a.Id == item.Id).ToOne();
var item2 = new TableAllType {
testFieldBool = true,
testFieldBoolNullable = true,
testFieldByte = 255,
testFieldByteNullable = 127,
testFieldBytes = Encoding.UTF8.GetBytes("ÎŇĘÇÖĐšúČË"),
testFieldDateTime = DateTime.Now,
testFieldDateTimeNullable = DateTime.Now.AddHours(-1),
testFieldDecimal = 99.99M,
testFieldDecimalNullable = 99.98M,
testFieldDouble = 999.99,
testFieldDoubleNullable = 999.98,
testFieldEnum1 = TableAllTypeEnumType1.e5,
testFieldEnum1Nullable = TableAllTypeEnumType1.e3,
testFieldEnum2 = TableAllTypeEnumType2.f2,
testFieldEnum2Nullable = TableAllTypeEnumType2.f3,
testFieldFloat = 19.99F,
testFieldFloatNullable = 19.98F,
testFieldGuid = Guid.NewGuid(),
testFieldGuidNullable = Guid.NewGuid(),
testFieldInt = int.MaxValue,
testFieldIntNullable = int.MinValue,
testFieldLineString = new MygisLineString(new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) }),
testFieldLong = long.MaxValue,
testFieldMultiLineString = new MygisMultiLineString(new[] {
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) },
new[] { new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 100) } }),
testFieldMultiPoint = new MygisMultiPoint(new[] { new MygisCoordinate2D(11, 11), new MygisCoordinate2D(51, 11) }),
testFieldMultiPolygon = new MygisMultiPolygon(new[] {
new MygisPolygon(new[] {
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }),
new MygisPolygon(new[] {
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }) }),
testFieldPoint = new MygisPoint(99, 99),
testFieldPolygon = new MygisPolygon(new[] {
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) },
new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }),
testFieldSByte = 100,
testFieldSByteNullable = 99,
testFieldShort = short.MaxValue,
testFieldShortNullable = short.MinValue,
testFieldString = "ÎŇĘÇÖĐšúČËstring",
testFieldTimeSpan = TimeSpan.FromSeconds(999),
testFieldTimeSpanNullable = TimeSpan.FromSeconds(60),
testFieldUInt = uint.MaxValue,
testFieldUIntNullable = uint.MinValue,
testFieldULong = ulong.MaxValue,
testFieldULongNullable = ulong.MinValue,
testFieldUShort = ushort.MaxValue,
testFieldUShortNullable = ushort.MinValue,
testFielLongNullable = long.MinValue
};
item2.Id = (int)insert.AppendData(item2).ExecuteIdentity();
var newitem2 = select.Where(a => a.Id == item2.Id).ToOne();
var items = select.ToList();
}
[JsonObject(MemberSerialization.OptIn), Table(Name = "tb_alltype")] [JsonObject(MemberSerialization.OptIn), Table(Name = "tb_alltype")]
public partial class Tb_alltype { public partial class Tb_alltype {

View File

@ -1,6 +1,7 @@
using FreeSql.DataAnnotations; using FreeSql.DataAnnotations;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using Npgsql;
using Npgsql.LegacyPostgis; using Npgsql.LegacyPostgis;
using NpgsqlTypes; using NpgsqlTypes;
using System; using System;
@ -9,6 +10,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.NetworkInformation; using System.Net.NetworkInformation;
using System.Text;
using Xunit; using Xunit;
namespace FreeSql.Tests.PostgreSQL { namespace FreeSql.Tests.PostgreSQL {
@ -49,7 +51,236 @@ namespace FreeSql.Tests.PostgreSQL {
g.pgsql.Select<TableAllType>(); g.pgsql.Select<TableAllType>();
} }
IInsert<TableAllType> insert => g.pgsql.Insert<TableAllType>();
ISelect<TableAllType> select => g.pgsql.Select<TableAllType>();
[Fact]
public void CurdAllField() {
NpgsqlConnection.GlobalTypeMapper.UseLegacyPostgis();
var item = new TableAllType { };
item.Id = (int)insert.AppendData(item).ExecuteIdentity();
var newitem = select.Where(a => a.Id == item.Id).ToOne();
var item2 = new TableAllType {
testFieldBitArray = new BitArray(Encoding.UTF8.GetBytes("我是")),
testFieldBitArrayArray = new[] { new BitArray(Encoding.UTF8.GetBytes("中国")), new BitArray(Encoding.UTF8.GetBytes("公民")) },
testFieldBool = true,
testFieldBoolArray = new[] { true, true, false, false },
testFieldBoolArrayNullable = new bool?[] { true, true, null, false, false },
testFieldBoolNullable = true,
testFieldByte = byte.MaxValue,
testFieldByteArray = new byte[] { 0, 1, 2, 3, 4, 5, 6 },
testFieldByteArrayNullable = new byte?[] { 0, 1, 2, 3, null, 4, 5, 6 },
testFieldByteNullable = byte.MinValue,
testFieldBytes = Encoding.UTF8.GetBytes("我是中国人"),
testFieldBytesArray = new[] { Encoding.UTF8.GetBytes("我是中国人"), Encoding.UTF8.GetBytes("我是中国人") },
testFieldCidr = (IPAddress.Parse("10.0.0.0"), 8),
testFieldCidrArray = new[] { (IPAddress.Parse("10.0.0.0"), 8), (IPAddress.Parse("192.168.0.0"), 16) },
testFieldCidrArrayNullable = new (IPAddress, int)?[] { (IPAddress.Parse("10.0.0.0"), 8), null, (IPAddress.Parse("192.168.0.0"), 16) },
testFieldCidrNullable = (IPAddress.Parse("192.168.0.0"), 16),
testFieldDateTime = DateTime.Now,
testFieldDateTimeArray = new[] { DateTime.Now, DateTime.Now.AddHours(2) },
testFieldDateTimeArrayNullable = new DateTime?[] { DateTime.Now, null, DateTime.Now.AddHours(2) },
testFieldDateTimeNullable = DateTime.Now.AddDays(-1),
testFieldDecimal = 999.99M,
testFieldDecimalArray = new[] { 999.91M, 999.92M, 999.93M },
testFieldDecimalArrayNullable = new decimal?[] { 998.11M, 998.12M, 998.13M },
testFieldDecimalNullable = 111.11M,
testFieldDouble = 888.88,
testFieldDoubleArray = new[] { 888.81, 888.82, 888.83 },
testFieldDoubleArrayNullable = new double?[] { 888.11, 888.12, null, 888.13 },
testFieldDoubleNullable = 222.22,
testFieldEnum1 = TableAllTypeEnumType1.e3,
testFieldEnum1Array = new[] { TableAllTypeEnumType1.e5, TableAllTypeEnumType1.e2, TableAllTypeEnumType1.e1 },
testFieldEnum1ArrayNullable = new TableAllTypeEnumType1?[] { TableAllTypeEnumType1.e5, TableAllTypeEnumType1.e2, null, TableAllTypeEnumType1.e1 },
testFieldEnum1Nullable = TableAllTypeEnumType1.e2,
testFieldEnum2 = TableAllTypeEnumType2.f2,
testFieldEnum2Array = new[] { TableAllTypeEnumType2.f3, TableAllTypeEnumType2.f1 },
testFieldEnum2ArrayNullable = new TableAllTypeEnumType2?[] { TableAllTypeEnumType2.f3, null, TableAllTypeEnumType2.f1 },
testFieldEnum2Nullable = TableAllTypeEnumType2.f3,
testFieldFloat = 777.77F,
testFieldFloatArray = new[] { 777.71F, 777.72F, 777.73F },
testFieldFloatArrayNullable = new float?[] { 777.71F, 777.72F, null, 777.73F },
testFieldFloatNullable = 333.33F,
testFieldGuid = Guid.NewGuid(),
testFieldGuidArray = new[] { Guid.NewGuid(), Guid.NewGuid() },
testFieldGuidArrayNullable = new Guid?[] { Guid.NewGuid(), null, Guid.NewGuid() },
testFieldGuidNullable = Guid.NewGuid(),
testFieldHStore = new Dictionary<string, string> { { "111", "value111" }, { "222", "value222" }, { "333", "value333" } },
testFieldHStoreArray = new[] { new Dictionary<string, string> { { "111", "value111" }, { "222", "value222" }, { "333", "value333" } }, new Dictionary<string, string> { { "444", "value444" }, { "555", "value555" }, { "666", "value666" } } },
testFieldInet = IPAddress.Parse("192.168.1.1"),
testFieldInetArray = new[] { IPAddress.Parse("192.168.1.1"), IPAddress.Parse("192.168.1.2"), IPAddress.Parse("192.168.1.3") },
testFieldInt = int.MaxValue,
testFieldInt4range = new NpgsqlRange<int>(10, 20),
testFieldInt4rangeArray = new[] { new NpgsqlRange<int>(10, 20), new NpgsqlRange<int>(50, 100), new NpgsqlRange<int>(200, 300) },
testFieldInt4rangeArrayNullable = new NpgsqlRange<int>?[] { new NpgsqlRange<int>(10, 20), new NpgsqlRange<int>(50, 100), null, new NpgsqlRange<int>(200, 300) },
testFieldInt4rangeNullable = new NpgsqlRange<int>(100, 200),
testFieldInt8range = new NpgsqlRange<long>(100, 200),
testFieldInt8rangeArray = new[] { new NpgsqlRange<long>(100, 200), new NpgsqlRange<long>(500, 1000), new NpgsqlRange<long>(2000, 3000) },
testFieldInt8rangeArrayNullable = new NpgsqlRange<long>?[] { new NpgsqlRange<long>(100, 200), new NpgsqlRange<long>(500, 1000), null, new NpgsqlRange<long>(2000, 3000) },
testFieldInt8rangeNullable = new NpgsqlRange<long>(1000, 2000),
testFieldIntArray = new[] { 1, 2, 3, 4, 5 },
testFieldIntArrayNullable = new int?[] { 1, 2, 3, null, 4, 5 },
testFieldIntNullable = int.MinValue,
testFieldJArray = JArray.Parse("[1,2,3,4,5]"),
testFieldJArrayArray = new[] { JArray.Parse("[1,2,3,4,5]"), JArray.Parse("[10,20,30,40,50]") },
testFieldJObject = JObject.Parse("{ \"a\":1, \"b\":2, \"c\":3 }"),
testFieldJObjectArray = new[] { JObject.Parse("{ \"a\":1, \"b\":2, \"c\":3 }"), JObject.Parse("{ \"a\":10, \"b\":20, \"c\":30 }") },
testFieldJToken = JToken.Parse("{ \"a\":1, \"b\":2, \"c\":3, \"d\":[1,2,3,4,5] }"),
testFieldJTokenArray = new[] { JToken.Parse("{ \"a\":1, \"b\":2, \"c\":3, \"d\":[1,2,3,4,5] }"), JToken.Parse("{ \"a\":10, \"b\":20, \"c\":30, \"d\":[10,20,30,40,50] }") },
testFieldLong = long.MaxValue,
testFieldLongArray = new long[] { 10, 20, 30, 40, 50 },
testFieldMacaddr = PhysicalAddress.Parse("A1-A2-CD-DD-FF-02"),
testFieldMacaddrArray = new[] { PhysicalAddress.Parse("A1-A2-CD-DD-FF-02"), PhysicalAddress.Parse("A2-22-22-22-22-02") },
testFieldNpgsqlBox = new NpgsqlBox(10, 100, 100, 10),
testFieldNpgsqlBoxArray = new[] { new NpgsqlBox(10, 100, 100, 10), new NpgsqlBox(200, 2000, 2000, 200) },
testFieldNpgsqlBoxArrayNullable = new NpgsqlBox?[] { new NpgsqlBox(10, 100, 100, 10), null, new NpgsqlBox(200, 2000, 2000, 200) },
testFieldNpgsqlBoxNullable = new NpgsqlBox(200, 2000, 2000, 200),
testFieldNpgsqlCircle = new NpgsqlCircle(50, 50, 100),
testFieldNpgsqlCircleArray = new[] { new NpgsqlCircle(50, 50, 100), new NpgsqlCircle(80, 80, 100) },
testFieldNpgsqlCircleArrayNullable = new NpgsqlCircle?[] { new NpgsqlCircle(50, 50, 100), null, new NpgsqlCircle(80, 80, 100) },
testFieldNpgsqlCircleNullable = new NpgsqlCircle(80, 80, 100),
testFieldNpgsqlLine = new NpgsqlLine(30, 30, 30),
testFieldNpgsqlLineArray = new[] { new NpgsqlLine(30, 30, 30), new NpgsqlLine(35, 35, 35) },
testFieldNpgsqlLineArrayNullable = new NpgsqlLine?[] { new NpgsqlLine(30, 30, 30), null, new NpgsqlLine(35, 35, 35) },
testFieldNpgsqlLineNullable = new NpgsqlLine(60, 60, 60),
testFieldNpgsqlLSeg = new NpgsqlLSeg(80, 10, 800, 20),
testFieldNpgsqlLSegArray = new[] { new NpgsqlLSeg(80, 10, 800, 20), new NpgsqlLSeg(180, 20, 260, 50) },
testFieldNpgsqlLSegArrayNullable = new NpgsqlLSeg?[] { new NpgsqlLSeg(80, 10, 800, 20), null, new NpgsqlLSeg(180, 20, 260, 50) },
testFieldNpgsqlLSegNullable = new NpgsqlLSeg(180, 20, 260, 50),
testFieldNpgsqlPath = new NpgsqlPath(new NpgsqlPoint(10, 10), new NpgsqlPoint(15, 10), new NpgsqlPoint(17, 10), new NpgsqlPoint(19, 10)),
testFieldNpgsqlPathArray = new[] { new NpgsqlPath(new NpgsqlPoint(10, 10), new NpgsqlPoint(15, 10), new NpgsqlPoint(17, 10), new NpgsqlPoint(19, 10)), new NpgsqlPath(new NpgsqlPoint(210, 10), new NpgsqlPoint(215, 10), new NpgsqlPoint(217, 10), new NpgsqlPoint(219, 10)) },
testFieldNpgsqlPathArrayNullable = new NpgsqlPath?[] { new NpgsqlPath(new NpgsqlPoint(10, 10), new NpgsqlPoint(15, 10), new NpgsqlPoint(17, 10), new NpgsqlPoint(19, 10)), null, new NpgsqlPath(new NpgsqlPoint(210, 10), new NpgsqlPoint(215, 10), new NpgsqlPoint(217, 10), new NpgsqlPoint(219, 10)) },
testFieldNpgsqlPathNullable = new NpgsqlPath(new NpgsqlPoint(210, 10), new NpgsqlPoint(215, 10), new NpgsqlPoint(217, 10), new NpgsqlPoint(219, 10)),
testFieldNpgsqlPoint = new NpgsqlPoint(666, 666),
testFieldNpgsqlPointArray = new[] { new NpgsqlPoint(666, 666), new NpgsqlPoint(888, 888) },
testFieldNpgsqlPointArrayNullable = new NpgsqlPoint?[] { new NpgsqlPoint(666, 666), null, new NpgsqlPoint(888, 888) },
testFieldNpgsqlPointNullable = new NpgsqlPoint(888, 888),
testFieldNpgsqlPolygon = new NpgsqlPolygon(new NpgsqlPoint(36, 30), new NpgsqlPoint(36, 50), new NpgsqlPoint(38, 80), new NpgsqlPoint(36, 30)),
testFieldNpgsqlPolygonArray = new[] { new NpgsqlPolygon(new NpgsqlPoint(36, 30), new NpgsqlPoint(36, 50), new NpgsqlPoint(38, 80), new NpgsqlPoint(36, 30)), new NpgsqlPolygon(new NpgsqlPoint(136, 130), new NpgsqlPoint(136, 150), new NpgsqlPoint(138, 180), new NpgsqlPoint(136, 130)) },
testFieldNpgsqlPolygonArrayNullable = new NpgsqlPolygon?[] { new NpgsqlPolygon(new NpgsqlPoint(36, 30), new NpgsqlPoint(36, 50), new NpgsqlPoint(38, 80), new NpgsqlPoint(36, 30)), null, new NpgsqlPolygon(new NpgsqlPoint(136, 130), new NpgsqlPoint(136, 150), new NpgsqlPoint(138, 180), new NpgsqlPoint(136, 130)) },
testFieldNpgsqlPolygonNullable = new NpgsqlPolygon(new NpgsqlPoint(136, 130), new NpgsqlPoint(136, 150), new NpgsqlPoint(138, 180), new NpgsqlPoint(136, 130)),
testFieldNumrange = new NpgsqlRange<decimal>(888.88M, 999.99M),
testFieldNumrangeArray = new[] { new NpgsqlRange<decimal>(888.88M, 999.99M), new NpgsqlRange<decimal>(18888.88M, 19998.99M) },
testFieldNumrangeArrayNullable = new NpgsqlRange<decimal>?[] { new NpgsqlRange<decimal>(888.88M, 999.99M), null, new NpgsqlRange<decimal>(18888.88M, 19998.99M) },
testFieldNumrangeNullable = new NpgsqlRange<decimal>(18888.88M, 19998.99M),
testFieldPostgisGeometry = new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }),
testFieldPostgisGeometryArray = new PostgisGeometry[] {
new PostgisPoint(555,551),
new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }),
new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }),
new PostgisMultiLineString(new[] { new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }) , new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 210) }) }),
new PostgisMultiPoint(new[] { new Coordinate2D(20, 21), new Coordinate2D(210, 220) }),
new PostgisMultiPolygon(new []{
new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }),
new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } })
})
},
testFieldPostgisGeometryCollection = new PostgisGeometryCollection(new PostgisGeometry[] {
new PostgisPoint(555,551),
new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }),
new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }),
new PostgisMultiLineString(new[] { new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }) , new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 210) }) }),
new PostgisMultiPoint(new[] { new Coordinate2D(20, 21), new Coordinate2D(210, 220) }),
new PostgisMultiPolygon(new []{
new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }),
new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } })
})
}),
testFieldPostgisGeometryCollectionArray = new[] {
new PostgisGeometryCollection(new PostgisGeometry[] {
new PostgisPoint(555,551),
new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }),
new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }),
new PostgisMultiLineString(new[] { new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }) , new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 210) }) }),
new PostgisMultiPoint(new[] { new Coordinate2D(20, 21), new Coordinate2D(210, 220) }),
new PostgisMultiPolygon(new []{
new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }),
new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } })
})
}),new PostgisGeometryCollection(new PostgisGeometry[] {
new PostgisPoint(555,551),
new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }),
new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }),
new PostgisMultiLineString(new[] { new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }) , new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 210) }) }),
new PostgisMultiPoint(new[] { new Coordinate2D(20, 21), new Coordinate2D(210, 220) }),
new PostgisMultiPolygon(new []{
new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }),
new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } })
})
})
},
testFieldPostgisLineString = new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }),
testFieldPostgisLineStringArray = new[] { new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }), new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 220) }) },
testFieldPostgisMultiPoint = new PostgisMultiPoint(new[] { new Coordinate2D(20, 21), new Coordinate2D(210, 220) }),
testFieldPostgisMultiPointArray = new[] { new PostgisMultiPoint(new[] { new Coordinate2D(20, 21), new Coordinate2D(210, 220) }), new PostgisMultiPoint(new[] { new Coordinate2D(120, 121), new Coordinate2D(1210, 1220) }) },
testFieldPostgisPoint = new PostgisPoint(555, 551),
testFieldPostgisPointArray = new[] { new PostgisPoint(555, 551), new PostgisPoint(53355, 3551) },
testFieldPostgisPolygon = new PostgisPolygon(new[] { new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }),
testFieldPostgisPolygonArray = new[]{
new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }),
new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } })
},
testFieldPostgisPostgisMultiLineString = new PostgisMultiLineString(new[] { new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }), new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 210) }) }),
testFieldPostgisPostgisMultiLineStringArray = new[] {
new PostgisMultiLineString(new[] { new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }) , new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 210) }) }),
new PostgisMultiLineString(new[] { new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 220) }) , new PostgisLineString(new[] { new Coordinate2D(820, 821), new Coordinate2D(800, 810) }) })
},
testFieldPostgisPostgisMultiPolygon = new PostgisMultiPolygon(new[]{
new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }),
new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } })
}),
testFieldPostgisPostgisMultiPolygonArray = new[] {
new PostgisMultiPolygon(new[]{
new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }),
new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } })
}),
new PostgisMultiPolygon(new[]{
new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }),
new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } })
})
},
testFieldSByte = sbyte.MaxValue,
testFieldSByteArray = new sbyte[] { 1, 2, 3, 4, 5 },
testFieldSByteArrayNullable = new sbyte?[] { 1, 2, 3, null, 4, 5 },
testFieldSByteNullable = sbyte.MinValue,
testFieldShort = short.MaxValue,
testFieldShortArray = new short[] { 1, 2, 3, 4, 5 },
testFieldShortArrayNullable = new short?[] { 1, 2, 3, null, 4, 5 },
testFieldShortNullable = short.MinValue,
testFieldString = "我是中国人String",
testFieldStringArray = new[] { "我是中国人String1", "我是中国人String2", null, "我是中国人String3" },
testFieldTimeSpan = TimeSpan.FromDays(1),
testFieldTimeSpanArray = new[] { TimeSpan.FromDays(1), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(60) },
testFieldTimeSpanArrayNullable = new TimeSpan?[] { TimeSpan.FromDays(1), TimeSpan.FromSeconds(10), null, TimeSpan.FromSeconds(60) },
testFieldTimeSpanNullable = TimeSpan.FromSeconds(90),
testFieldTsrange = new NpgsqlRange<DateTime>(DateTime.Now, DateTime.Now.AddMonths(1)),
testFieldTsrangeArray = new[] { new NpgsqlRange<DateTime>(DateTime.Now, DateTime.Now.AddMonths(1)), new NpgsqlRange<DateTime>(DateTime.Now, DateTime.Now.AddMonths(2)) },
testFieldTsrangeArrayNullable = new NpgsqlRange<DateTime>?[] { new NpgsqlRange<DateTime>(DateTime.Now, DateTime.Now.AddMonths(1)), null, new NpgsqlRange<DateTime>(DateTime.Now, DateTime.Now.AddMonths(2)) },
testFieldTsrangeNullable = new NpgsqlRange<DateTime>(DateTime.Now, DateTime.Now.AddMonths(2)),
testFieldUInt = uint.MaxValue,
testFieldUIntArray = new uint[] { 1, 2, 3, 4, 5 },
testFieldUIntArrayNullable = new uint?[] { 1, 2, 3, null, 4, 5 },
testFieldUIntNullable = uint.MinValue,
testFieldULong = ulong.MaxValue,
testFieldULongArray = new ulong[] { 10, 20, 30, 40, 50 },
testFieldULongArrayNullable = new ulong?[] { 10, 20, 30, null, 40, 50 },
testFieldULongNullable = ulong.MinValue,
testFieldUShort = ushort.MaxValue,
testFieldUShortArray = new ushort[] { 11, 12, 13, 14, 15 },
testFieldUShortArrayNullable = new ushort?[] { 11, 12, 13, null, 14, 15 },
testFieldUShortNullable = ushort.MinValue,
testFielLongArrayNullable = new long?[] { 500, 600, 700, null, 999, 1000 },
testFielLongNullable = long.MinValue
};
item2.Id = (int)insert.AppendData(item2).ExecuteIdentity();
var newitem2 = select.Where(a => a.Id == item2.Id).ToOne();
var items = select.ToList();
}
[Table(Name = "tb_alltype")] [Table(Name = "tb_alltype")]
class TableAllType { class TableAllType {
[Column(IsIdentity = true, IsPrimary = true)] [Column(IsIdentity = true, IsPrimary = true)]

View File

@ -3,6 +3,7 @@ using Newtonsoft.Json;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
using Xunit; using Xunit;
namespace FreeSql.Tests.SqlServer { namespace FreeSql.Tests.SqlServer {
@ -40,6 +41,63 @@ namespace FreeSql.Tests.SqlServer {
sql = g.sqlserver.CodeFirst.GetComparisonDDLStatements<Tb_alltype>(); sql = g.sqlserver.CodeFirst.GetComparisonDDLStatements<Tb_alltype>();
} }
IInsert<TableAllType> insert => g.sqlserver.Insert<TableAllType>();
ISelect<TableAllType> select => g.sqlserver.Select<TableAllType>();
[Fact]
public void CurdAllField() {
var item = new TableAllType { };
item.Id = (int)insert.AppendData(item).ExecuteIdentity();
var newitem = select.Where(a => a.Id == item.Id).ToOne();
var item2 = new TableAllType {
testFieldBool = true,
testFieldBoolNullable = true,
testFieldByte = byte.MaxValue,
testFieldByteNullable = byte.MinValue,
testFieldBytes = Encoding.UTF8.GetBytes("ÎÒÊÇÖйúÈË"),
testFieldDateTime = DateTime.Now,
testFieldDateTimeNullable = DateTime.Now.AddHours(1),
testFieldDateTimeNullableOffset = new DateTimeOffset(DateTime.Now.AddHours(1), TimeSpan.FromHours(8)),
testFieldDateTimeOffset = new DateTimeOffset(DateTime.Now, TimeSpan.FromHours(8)),
testFieldDecimal = 998.99M,
testFieldDecimalNullable = 999.12M,
testFieldDouble = 99.199,
testFieldDoubleNullable = 99.211,
testFieldEnum1 = TableAllTypeEnumType1.e2,
testFieldEnum1Nullable = TableAllTypeEnumType1.e3,
testFieldEnum2 = TableAllTypeEnumType2.f3,
testFieldEnum2Nullable = TableAllTypeEnumType2.f2,
testFieldFloat = 0.99F,
testFieldFloatNullable = 0.11F,
testFieldGuid = Guid.NewGuid(),
testFieldGuidNullable = Guid.NewGuid(),
testFieldInt = int.MaxValue,
testFieldIntNullable = int.MinValue,
testFieldLong = long.MaxValue,
testFieldSByte = sbyte.MaxValue,
testFieldSByteNullable = sbyte.MinValue,
testFieldShort = short.MaxValue,
testFieldShortNullable = short.MinValue,
testFieldString = "ÎÒÊÇÖйúÈËstring",
testFieldTimeSpan = TimeSpan.FromSeconds(999),
testFieldTimeSpanNullable = TimeSpan.FromSeconds(30),
testFieldUInt = uint.MaxValue,
testFieldUIntNullable = uint.MinValue,
testFieldULong = ulong.MaxValue,
testFieldULongNullable = ulong.MinValue,
testFieldUShort = ushort.MaxValue,
testFieldUShortNullable = ushort.MinValue,
testFielLongNullable = long.MinValue
};
item2.Id = (int)insert.AppendData(item2).ExecuteIdentity();
var newitem2 = select.Where(a => a.Id == item2.Id).ToOne();
var items = select.ToList();
}
[JsonObject(MemberSerialization.OptIn), Table(Name = "dbo.tb_alltype")] [JsonObject(MemberSerialization.OptIn), Table(Name = "dbo.tb_alltype")]
public partial class Tb_alltype { public partial class Tb_alltype {
@ -199,7 +257,7 @@ namespace FreeSql.Tests.SqlServer {
public long? TestFielLongNullable { get; set; } public long? TestFielLongNullable { get; set; }
} }
[Table(Name = "tb_alltype")] [Table(Name = "tb_alltype")]
class TableAllType { class TableAllType {
[Column(IsIdentity = true, IsPrimary = true)] [Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; } public int Id { get; set; }

View File

@ -7,17 +7,17 @@ public class g {
public static IFreeSql mysql = new FreeSql.FreeSqlBuilder() public static IFreeSql mysql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=10") .UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=10")
.UseAutoSyncStructure() .UseAutoSyncStructure(true)
.Build(); .Build();
public static IFreeSql sqlserver = new FreeSql.FreeSqlBuilder() public static IFreeSql sqlserver = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=cms;Pooling=true;Max Pool Size=10") .UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=cms;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure() .UseAutoSyncStructure(true)
.Build(); .Build();
public static IFreeSql pgsql = new FreeSql.FreeSqlBuilder() public static IFreeSql pgsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.PostgreSQL, "Host=192.168.164.10;Port=5432;Username=postgres;Password=123456;Database=tedb;Pooling=true;Maximum Pool Size=10") .UseConnectionString(FreeSql.DataType.PostgreSQL, "Host=192.168.164.10;Port=5432;Username=postgres;Password=123456;Database=tedb;Pooling=true;Maximum Pool Size=10")
.UseAutoSyncStructure() .UseAutoSyncStructure(true)
.UseSyncStructureToLower() .UseSyncStructureToLower(true)
.Build(); .Build();
} }

View File

@ -56,17 +56,19 @@ namespace FreeSql {
/// <summary> /// <summary>
/// 【开发环境必备】自动同步实体结构到数据库,程序运行中检查实体表是否存在,然后创建或修改 /// 【开发环境必备】自动同步实体结构到数据库,程序运行中检查实体表是否存在,然后创建或修改
/// </summary> /// </summary>
/// <param name="value">true:运行时检查自动同步结构, false:不同步结构</param>
/// <returns></returns> /// <returns></returns>
public FreeSqlBuilder UseAutoSyncStructure() { public FreeSqlBuilder UseAutoSyncStructure(bool value) {
_isAutoSyncStructure = true; _isAutoSyncStructure = value;
return this; return this;
} }
/// <summary> /// <summary>
/// 转小写同步结构 /// 转小写同步结构
/// </summary> /// </summary>
/// <param name="value">true:转小写, false:不转</param>
/// <returns></returns> /// <returns></returns>
public FreeSqlBuilder UseSyncStructureToLower() { public FreeSqlBuilder UseSyncStructureToLower(bool value) {
_isSyncStructureToLower = true; _isSyncStructureToLower = value;
return this; return this;
} }

View File

@ -40,7 +40,7 @@ namespace FreeSql.Internal {
parent.ConsturctorType = ReadAnonymousTypeInfoConsturctorType.Properties; parent.ConsturctorType = ReadAnonymousTypeInfoConsturctorType.Properties;
for (var idx = 0; idx < map.Count; idx++) { for (var idx = 0; idx < map.Count; idx++) {
var child = new ReadAnonymousTypeInfo { CsName = map[idx].Column.CsName, DbField = $"{map[idx].Table.Alias}.{_common.QuoteSqlName(map[idx].Column.Attribute.Name)}" }; var child = new ReadAnonymousTypeInfo { CsName = map[idx].Column.CsName, DbField = $"{map[idx].Table.Alias}.{_common.QuoteSqlName(map[idx].Column.Attribute.Name)}" };
field.Append(", ").Append(child.DbField).Append(" as").Append(++index); field.Append(", ").Append(_common.QuoteReadColumn(map[idx].Column.CsType, child.DbField)).Append(" as").Append(++index);
parent.Childs.Add(child); parent.Childs.Add(child);
} }
} else { } else {
@ -192,7 +192,7 @@ namespace FreeSql.Internal {
throw new Exception($"MySqlExpression 未现实函数表达式 {exp3} 解析"); throw new Exception($"MySqlExpression 未现实函数表达式 {exp3} 解析");
case ExpressionType.MemberAccess: case ExpressionType.MemberAccess:
var exp4 = exp as MemberExpression; var exp4 = exp as MemberExpression;
if (exp4.Expression != null && exp4.Expression.Type.FullName.StartsWith("System.Nullable`1[")) return ExpressionLambdaToSql(exp4.Expression, _tables, _selectColumnMap, tbtype, isQuoteName); if (exp4.Expression != null && exp4.Expression.Type.IsArray == false && exp4.Expression.Type.FullName.StartsWith("System.Nullable`1[")) return ExpressionLambdaToSql(exp4.Expression, _tables, _selectColumnMap, tbtype, isQuoteName);
var extRet = ""; var extRet = "";
switch (exp4.Expression?.Type.FullName ?? exp4.Type.FullName) { switch (exp4.Expression?.Type.FullName ?? exp4.Type.FullName) {
case "System.String": extRet = ExpressionLambdaToSqlMemberAccessString(exp4, _tables, _selectColumnMap, tbtype, isQuoteName); break; case "System.String": extRet = ExpressionLambdaToSqlMemberAccessString(exp4, _tables, _selectColumnMap, tbtype, isQuoteName); break;

View File

@ -38,7 +38,7 @@ namespace FreeSql.Internal.CommonProvider {
if (e == null) return; if (e == null) return;
string log = $"{pool.Policy.Name}数据库出错执行SQL〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓\r\n{cmd.CommandText}\r\n"; string log = $"{pool.Policy.Name}数据库出错执行SQL〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓\r\n{cmd.CommandText}\r\n";
foreach (DbParameter parm in cmd.Parameters) foreach (DbParameter parm in cmd.Parameters)
log += parm.ParameterName.PadRight(20, ' ') + " = " + (parm.Value ?? "NULL") + "\r\n"; log += parm.ParameterName.PadRight(20, ' ') + " = " + ((parm.Value ?? DBNull.Value) == DBNull.Value ? "NULL" : parm.Value) + "\r\n";
log += e.Message; log += e.Message;
_log.LogError(log); _log.LogError(log);

View File

@ -75,8 +75,8 @@ namespace FreeSql.Internal.CommonProvider {
foreach (var col in _table.Columns.Values) foreach (var col in _table.Columns.Values)
if (col.Attribute.IsIdentity == false && _ignore.ContainsKey(col.Attribute.Name) == false) { if (col.Attribute.IsIdentity == false && _ignore.ContainsKey(col.Attribute.Name) == false) {
if (colidx2 > 0) sb.Append(", "); if (colidx2 > 0) sb.Append(", ");
sb.Append(_commonUtils.QuoteParamterName(col.CsName)).Append(didx); sb.Append(_commonUtils.QuoteWriteParamter(col.CsType, $"{_commonUtils.QuoteParamterName(col.CsName)}{didx}"));
_params[didx * colidx + colidx2] = _commonUtils.AppendParamter(null, $"{col.CsName}{didx}", _table.Properties.TryGetValue(col.CsName, out var tryp) ? tryp.GetValue(d) : DBNull.Value); _params[didx * colidx + colidx2] = _commonUtils.AppendParamter(null, $"{col.CsName}{didx}", col.CsType, _table.Properties.TryGetValue(col.CsName, out var tryp) ? tryp.GetValue(d) : null);
++colidx2; ++colidx2;
} }
sb.Append(")"); sb.Append(")");

View File

@ -187,7 +187,7 @@ namespace FreeSql.Internal.CommonProvider {
if (tb.Table.ColumnsByCs.TryGetValue(p.Name, out var col)) { //普通字段 if (tb.Table.ColumnsByCs.TryGetValue(p.Name, out var col)) { //普通字段
if (index > 0) field.Append(", "); if (index > 0) field.Append(", ");
var quoteName = _commonUtils.QuoteSqlName(col.Attribute.Name); var quoteName = _commonUtils.QuoteSqlName(col.Attribute.Name);
field.Append(tb.Alias).Append(".").Append(quoteName); field.Append(_commonUtils.QuoteReadColumn(col.CsType, $"{tb.Alias}.{quoteName}"));
++index; ++index;
if (dicfield.ContainsKey(quoteName)) field.Append(" as").Append(index); if (dicfield.ContainsKey(quoteName)) field.Append(" as").Append(index);
else dicfield.Add(quoteName, true); else dicfield.Add(quoteName, true);
@ -200,7 +200,7 @@ namespace FreeSql.Internal.CommonProvider {
foreach (var col2 in tb2.Table.Columns.Values) { foreach (var col2 in tb2.Table.Columns.Values) {
if (index > 0) field.Append(", "); if (index > 0) field.Append(", ");
var quoteName = _commonUtils.QuoteSqlName(col2.Attribute.Name); var quoteName = _commonUtils.QuoteSqlName(col2.Attribute.Name);
field.Append(tb2.Alias).Append(".").Append(quoteName); field.Append(_commonUtils.QuoteReadColumn(col.CsType, $"{tb2.Alias}.{quoteName}"));
++index; ++index;
if (dicfield.ContainsKey(quoteName)) field.Append(" as").Append(index); if (dicfield.ContainsKey(quoteName)) field.Append(" as").Append(index);
else dicfield.Add(quoteName, true); else dicfield.Add(quoteName, true);

View File

@ -52,10 +52,12 @@ namespace FreeSql.Internal.CommonProvider {
} }
public IUpdate<T1> Set<TMember>(Expression<Func<T1, TMember>> column, TMember value) { public IUpdate<T1> Set<TMember>(Expression<Func<T1, TMember>> column, TMember value) {
var col = _commonExpression.ExpressionSelectColumn_MemberAccess(null, null, SelectTableInfoType.From, column?.Body, true); var cols = new List<SelectColumnInfo>();
if (string.IsNullOrEmpty(col)) return this; _commonExpression.ExpressionSelectColumn_MemberAccess(null, cols, SelectTableInfoType.From, column?.Body, true);
_set.Append(", ").Append(col).Append(" = ").Append(_commonUtils.QuoteParamterName("p_")).Append(_params.Count); if (cols.Count != 1) return this;
_commonUtils.AppendParamter(_params, null, value); var col = cols.First();
_set.Append(", ").Append(_commonUtils.QuoteSqlName(col.Column.Attribute.Name)).Append(" = ").Append(_commonUtils.QuoteWriteParamter(col.Column.CsType, $"{_commonUtils.QuoteParamterName("p_")}{_params.Count}"));
_commonUtils.AppendParamter(_params, null, col.Column.CsType, value);
//foreach (var t in _source) Utils.FillPropertyValue(t, tryf.CsName, value); //foreach (var t in _source) Utils.FillPropertyValue(t, tryf.CsName, value);
return this; return this;
} }
@ -111,8 +113,8 @@ namespace FreeSql.Internal.CommonProvider {
foreach (var col in _table.Columns.Values) { foreach (var col in _table.Columns.Values) {
if (col.Attribute.IsIdentity == false && _ignore.ContainsKey(col.CsName) == false) { if (col.Attribute.IsIdentity == false && _ignore.ContainsKey(col.CsName) == false) {
if (colidx > 0) sb.Append(", "); if (colidx > 0) sb.Append(", ");
sb.Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" = ").Append(_commonUtils.QuoteParamterName($"p_{_paramsSource.Count}")); sb.Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" = ").Append(_commonUtils.QuoteWriteParamter(col.CsType, _commonUtils.QuoteParamterName($"p_{_paramsSource.Count}")));
_commonUtils.AppendParamter(_paramsSource, null, _table.Properties.TryGetValue(col.CsName, out var tryp) ? tryp.GetValue(_source.First()) : DBNull.Value); _commonUtils.AppendParamter(_paramsSource, null, col.CsType, _table.Properties.TryGetValue(col.CsName, out var tryp) ? tryp.GetValue(_source.First()) : null);
++colidx; ++colidx;
} }
} }
@ -151,8 +153,8 @@ namespace FreeSql.Internal.CommonProvider {
// ++pkidx; // ++pkidx;
//} //}
//if (_table.Primarys.Length > 1) sb.Append(")"); //if (_table.Primarys.Length > 1) sb.Append(")");
sb.Append(" THEN ").Append(_commonUtils.QuoteParamterName($"p_{_paramsSource.Count}")); sb.Append(" THEN ").Append(_commonUtils.QuoteWriteParamter(col.CsType, _commonUtils.QuoteParamterName($"p_{_paramsSource.Count}")));
_commonUtils.AppendParamter(_paramsSource, null, _table.Properties.TryGetValue(col.CsName, out var tryp) ? tryp.GetValue(d) : DBNull.Value); _commonUtils.AppendParamter(_paramsSource, null, col.CsType, _table.Properties.TryGetValue(col.CsName, out var tryp) ? tryp.GetValue(d) : DBNull.Value);
} }
sb.Append(" END"); sb.Append(" END");
++colidx; ++colidx;

View File

@ -11,12 +11,14 @@ namespace FreeSql.Internal {
internal abstract class CommonUtils { internal abstract class CommonUtils {
internal abstract DbParameter[] GetDbParamtersByObject(string sql, object obj); internal abstract DbParameter[] GetDbParamtersByObject(string sql, object obj);
internal abstract DbParameter AppendParamter(List<DbParameter> _params, string parameterName, object value); internal abstract DbParameter AppendParamter(List<DbParameter> _params, string parameterName, Type type, object value);
internal abstract string FormatSql(string sql, params object[] args); internal abstract string FormatSql(string sql, params object[] args);
internal abstract string QuoteSqlName(string name); internal abstract string QuoteSqlName(string name);
internal abstract string QuoteParamterName(string name); internal abstract string QuoteParamterName(string name);
internal abstract string IsNull(string sql, object value); internal abstract string IsNull(string sql, object value);
internal abstract string StringConcat(string left, string right, Type leftType, Type rightType); internal abstract string StringConcat(string left, string right, Type leftType, Type rightType);
internal abstract string QuoteWriteParamter(Type type, string paramterName);
internal abstract string QuoteReadColumn(Type type, string columnName);
internal ICodeFirst CodeFirst { get; set; } internal ICodeFirst CodeFirst { get; set; }
internal TableInfo GetTableByEntity(Type entity) => Utils.GetTableByEntity(entity, this); internal TableInfo GetTableByEntity(Type entity) => Utils.GetTableByEntity(entity, this);

View File

@ -1,5 +1,6 @@
using FreeSql.DataAnnotations; using FreeSql.DataAnnotations;
using FreeSql.Internal.Model; using FreeSql.Internal.Model;
using Newtonsoft.Json.Linq;
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
@ -14,7 +15,7 @@ namespace FreeSql.Internal {
static ConcurrentDictionary<string, TableInfo> _cacheGetTableByEntity = new ConcurrentDictionary<string, TableInfo>(); static ConcurrentDictionary<string, TableInfo> _cacheGetTableByEntity = new ConcurrentDictionary<string, TableInfo>();
internal static TableInfo GetTableByEntity(Type entity, CommonUtils common) { internal static TableInfo GetTableByEntity(Type entity, CommonUtils common) {
if (_cacheGetTableByEntity.TryGetValue(entity.FullName, out var trytb)) return trytb; if (_cacheGetTableByEntity.TryGetValue($"{common.QuoteSqlName("db")}{entity.FullName}", out var trytb)) return trytb; //区分数据库类型缓存
if (common.CodeFirst.GetDbInfo(entity) != null) return null; if (common.CodeFirst.GetDbInfo(entity) != null) return null;
var tbattr = entity.GetCustomAttributes(typeof(TableAttribute), false).LastOrDefault() as TableAttribute; var tbattr = entity.GetCustomAttributes(typeof(TableAttribute), false).LastOrDefault() as TableAttribute;
@ -145,8 +146,35 @@ namespace FreeSql.Internal {
} }
internal static object GetDataReaderValue(Type type, object value) { internal static object GetDataReaderValue(Type type, object value) {
if (value == null || value == DBNull.Value) return null; if (value == null || value == DBNull.Value) return null;
if (type.FullName == "System.Byte[]") return value;
if (type.IsArray) {
var elementType = type.GetElementType();
var valueArr = value as Array;
var len = valueArr.GetLength(0);
var ret = Array.CreateInstance(elementType, len);
for (var a = 0; a < len; a++) {
var item = valueArr.GetValue(a);
ret.SetValue(GetDataReaderValue(elementType, item), a);
}
return ret;
}
if (type.FullName.StartsWith("System.Nullable`1[")) type = type.GenericTypeArguments.First(); if (type.FullName.StartsWith("System.Nullable`1[")) type = type.GenericTypeArguments.First();
if (type.IsEnum) return Enum.Parse(type, string.Concat(value)); if (type.IsEnum) return Enum.Parse(type, string.Concat(value), true);
switch(type.FullName) {
case "System.Guid":
if (value.GetType() != type) return Guid.TryParse(string.Concat(value), out var tryguid) ? tryguid : Guid.Empty;
return value;
case "MygisPoint": return MygisPoint.Parse(string.Concat(value)) as MygisPoint;
case "MygisLineString": return MygisLineString.Parse(string.Concat(value)) as MygisLineString;
case "MygisPolygon": return MygisPolygon.Parse(string.Concat(value)) as MygisPolygon;
case "MygisMultiPoint": return MygisMultiPoint.Parse(string.Concat(value)) as MygisMultiPoint;
case "MygisMultiLineString": return MygisMultiLineString.Parse(string.Concat(value)) as MygisMultiLineString;
case "MygisMultiPolygon": return MygisMultiPolygon.Parse(string.Concat(value)) as MygisMultiPolygon;
case "Newtonsoft.Json.Linq.JToken": return JToken.Parse(string.Concat(value));
case "Newtonsoft.Json.Linq.JObject": return JObject.Parse(string.Concat(value));
case "Newtonsoft.Json.Linq.JArray": return JArray.Parse(string.Concat(value));
case "Npgsql.LegacyPostgis.PostgisGeometry": return value;
}
if (type != value.GetType()) return Convert.ChangeType(value, type); if (type != value.GetType()) return Convert.ChangeType(value, type);
return value; return value;
} }

View File

@ -17,7 +17,7 @@ namespace FreeSql.MySql.Curd {
var colidx = 0; var colidx = 0;
foreach (var col in _table.Columns.Values) { foreach (var col in _table.Columns.Values) {
if (colidx > 0) sb.Append(", "); if (colidx > 0) sb.Append(", ");
sb.Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); sb.Append(_commonUtils.QuoteReadColumn(col.CsType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName));
++colidx; ++colidx;
} }
return _orm.Ado.Query<T1>(CommandType.Text, sb.ToString(), _params.ToArray()); return _orm.Ado.Query<T1>(CommandType.Text, sb.ToString(), _params.ToArray());

View File

@ -19,7 +19,7 @@ namespace FreeSql.MySql.Curd {
var colidx = 0; var colidx = 0;
foreach (var col in _table.Columns.Values) { foreach (var col in _table.Columns.Values) {
if (colidx > 0) sb.Append(", "); if (colidx > 0) sb.Append(", ");
sb.Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); sb.Append(_commonUtils.QuoteReadColumn(col.CsType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName));
++colidx; ++colidx;
} }
return _orm.Ado.Query<T1>(CommandType.Text, sb.ToString(), _params); return _orm.Ado.Query<T1>(CommandType.Text, sb.ToString(), _params);

View File

@ -20,7 +20,7 @@ namespace FreeSql.MySql.Curd {
var colidx = 0; var colidx = 0;
foreach (var col in _table.Columns.Values) { foreach (var col in _table.Columns.Values) {
if (colidx > 0) sb.Append(", "); if (colidx > 0) sb.Append(", ");
sb.Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); sb.Append(_commonUtils.QuoteReadColumn(col.CsType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName));
++colidx; ++colidx;
} }
return _orm.Ado.Query<T1>(CommandType.Text, sb.ToString(), _params.Concat(_paramsSource).ToArray()); return _orm.Ado.Query<T1>(CommandType.Text, sb.ToString(), _params.Concat(_paramsSource).ToArray());
@ -28,14 +28,14 @@ namespace FreeSql.MySql.Curd {
protected override void ToSqlCase(StringBuilder caseWhen, ColumnInfo[] primarys) { protected override void ToSqlCase(StringBuilder caseWhen, ColumnInfo[] primarys) {
if (_table.Primarys.Length == 1) { if (_table.Primarys.Length == 1) {
caseWhen.Append(_commonUtils.QuoteSqlName(_table.Primarys.First().Attribute.Name)); caseWhen.Append(_commonUtils.QuoteReadColumn(_table.Primarys.First().CsType, _commonUtils.QuoteSqlName(_table.Primarys.First().Attribute.Name)));
return; return;
} }
caseWhen.Append("CONCAT("); caseWhen.Append("CONCAT(");
var pkidx = 0; var pkidx = 0;
foreach (var pk in _table.Primarys) { foreach (var pk in _table.Primarys) {
if (pkidx > 0) caseWhen.Append(", "); if (pkidx > 0) caseWhen.Append(", ");
caseWhen.Append(_commonUtils.QuoteSqlName(pk.Attribute.Name)); caseWhen.Append(_commonUtils.QuoteReadColumn(pk.CsType, _commonUtils.QuoteSqlName(pk.Attribute.Name)));
++pkidx; ++pkidx;
} }
caseWhen.Append(")"); caseWhen.Append(")");

View File

@ -42,6 +42,8 @@ namespace FreeSql.MySql {
return ((TimeSpan)param).Ticks / 10; return ((TimeSpan)param).Ticks / 10;
else if (param is TimeSpan?) else if (param is TimeSpan?)
return (param as TimeSpan?).Value.Ticks / 10; return (param as TimeSpan?).Value.Ticks / 10;
else if (param is MygisGeometry)
return (param as MygisGeometry).AsText();
else if (param is IEnumerable) { else if (param is IEnumerable) {
var sb = new StringBuilder(); var sb = new StringBuilder();
var ie = param as IEnumerable; var ie = param as IEnumerable;

View File

@ -39,7 +39,7 @@ public static partial class MygisTypesExtensions {
string value = dr.GetString(index); string value = dr.GetString(index);
Type t = typeof(T); Type t = typeof(T);
foreach (var f in t.GetFields()) foreach (var f in t.GetFields())
if (f.GetCustomAttribute<DescriptionAttribute>()?.Description == value || f.Name == value) return Enum.Parse(t, f.Name); if (f.GetCustomAttribute<DescriptionAttribute>()?.Description == value || f.Name == value) return Enum.Parse(t, f.Name, true);
return null; return null;
} }
@ -57,7 +57,7 @@ public static partial class MygisTypesExtensions {
Type t = typeof(T); Type t = typeof(T);
foreach (FieldInfo f in t.GetFields()) { foreach (FieldInfo f in t.GetFields()) {
if (f.FieldType != t) continue; if (f.FieldType != t) continue;
object o = Enum.Parse(t, f.Name); object o = Enum.Parse(t, f.Name, true);
long v = (long)o; long v = (long)o;
if ((value & v) == v) ret.Add((T)o); if ((value & v) == v) ret.Add((T)o);
} }

View File

@ -61,6 +61,7 @@ namespace FreeSql.MySql {
public (int type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfo(Type type) { public (int type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfo(Type type) {
if (_dicCsToDb.TryGetValue(type.FullName, out var trydc)) return new (int, string, string, bool?, object)?(((int)trydc.type, trydc.dbtype, trydc.dbtypeFull, trydc.isnullable, trydc.defaultValue)); if (_dicCsToDb.TryGetValue(type.FullName, out var trydc)) return new (int, string, string, bool?, object)?(((int)trydc.type, trydc.dbtype, trydc.dbtypeFull, trydc.isnullable, trydc.defaultValue));
if (type.IsArray) return null;
var enumType = type.IsEnum ? type : null; var enumType = type.IsEnum ? type : null;
if (enumType == null && type.FullName.StartsWith("System.Nullable`1[") && type.GenericTypeArguments.Length == 1 && type.GenericTypeArguments.First().IsEnum) enumType = type.GenericTypeArguments.First(); if (enumType == null && type.FullName.StartsWith("System.Nullable`1[") && type.GenericTypeArguments.Length == 1 && type.GenericTypeArguments.First().IsEnum) enumType = type.GenericTypeArguments.First();
if (enumType != null) { if (enumType != null) {

View File

@ -1,4 +1,5 @@
using FreeSql.Internal; using FreeSql.Internal;
using FreeSql.Internal.Model;
using MySql.Data.MySqlClient; using MySql.Data.MySqlClient;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -12,19 +13,17 @@ namespace FreeSql.MySql {
_orm = mysql; _orm = mysql;
} }
internal override DbParameter AppendParamter(List<DbParameter> _params, string parameterName, object value) { internal override DbParameter AppendParamter(List<DbParameter> _params, string parameterName, Type type, object value) {
if (string.IsNullOrEmpty(parameterName)) parameterName = $"p_{_params?.Count}"; if (string.IsNullOrEmpty(parameterName)) parameterName = $"p_{_params?.Count}";
else if (_orm.CodeFirst.IsSyncStructureToLower) parameterName = parameterName.ToLower(); else if (_orm.CodeFirst.IsSyncStructureToLower) parameterName = parameterName.ToLower();
MySqlParameter ret = null; var ret = new MySqlParameter { ParameterName = $"?{parameterName}", Value = value };
if (value == null) ret = new MySqlParameter { ParameterName = $"{parameterName}", Value = DBNull.Value }; var tp = _orm.CodeFirst.GetDbInfo(type)?.type;
else { if (tp != null) {
var type = value.GetType(); if ((MySqlDbType)tp.Value == MySqlDbType.Geometry) {
ret = new MySqlParameter { ret.MySqlDbType = MySqlDbType.Text;
ParameterName = parameterName, if (value != null) ret.Value = (value as MygisGeometry).AsText();
Value = value } else
}; ret.MySqlDbType = (MySqlDbType)tp.Value;
var tp = _orm.CodeFirst.GetDbInfo(type)?.type;
if (tp != null) ret.MySqlDbType = (MySqlDbType)tp.Value;
} }
_params?.Add(ret); _params?.Add(ret);
return ret; return ret;
@ -32,13 +31,16 @@ namespace FreeSql.MySql {
internal override DbParameter[] GetDbParamtersByObject(string sql, object obj) => internal override DbParameter[] GetDbParamtersByObject(string sql, object obj) =>
Utils.GetDbParamtersByObject<MySqlParameter>(sql, obj, "?", (name, type, value) => { Utils.GetDbParamtersByObject<MySqlParameter>(sql, obj, "?", (name, type, value) => {
var cp = new MySqlParameter { var ret = new MySqlParameter { ParameterName = $"?{name}", Value = value };
ParameterName = name,
Value = value ?? DBNull.Value
};
var tp = _orm.CodeFirst.GetDbInfo(type)?.type; var tp = _orm.CodeFirst.GetDbInfo(type)?.type;
if (tp != null) cp.MySqlDbType = (MySqlDbType)tp.Value; if (tp != null) {
return cp; if ((MySqlDbType)tp.Value == MySqlDbType.Geometry) {
ret.MySqlDbType = MySqlDbType.Text;
if (value != null) ret.Value = (value as MygisGeometry).AsText();
} else
ret.MySqlDbType = (MySqlDbType)tp.Value;
}
return ret;
}); });
internal override string FormatSql(string sql, params object[] args) => sql?.FormatMySql(args); internal override string FormatSql(string sql, params object[] args) => sql?.FormatMySql(args);
@ -46,5 +48,29 @@ namespace FreeSql.MySql {
internal override string QuoteParamterName(string name) => $"?{(_orm.CodeFirst.IsSyncStructureToLower ? name.ToLower() : name)}"; internal override string QuoteParamterName(string name) => $"?{(_orm.CodeFirst.IsSyncStructureToLower ? name.ToLower() : name)}";
internal override string IsNull(string sql, object value) => $"ifnull({sql}, {value})"; internal override string IsNull(string sql, object value) => $"ifnull({sql}, {value})";
internal override string StringConcat(string left, string right, Type leftType, Type rightType) => $"concat({left}, {right})"; internal override string StringConcat(string left, string right, Type leftType, Type rightType) => $"concat({left}, {right})";
internal override string QuoteWriteParamter(Type type, string paramterName) {
switch (type.FullName) {
case "MygisPoint":
case "MygisLineString":
case "MygisPolygon":
case "MygisMultiPoint":
case "MygisMultiLineString":
case "MygisMultiPolygon": return $"ST_GeomFromText({paramterName})";
}
return paramterName;
}
internal override string QuoteReadColumn(Type type, string columnName) {
switch (type.FullName) {
case "MygisPoint":
case "MygisLineString":
case "MygisPolygon":
case "MygisMultiPoint":
case "MygisMultiLineString":
case "MygisMultiPolygon": return $"AsText({columnName})";
}
return columnName;
}
} }
} }

View File

@ -17,7 +17,7 @@ namespace FreeSql.PostgreSQL.Curd {
var colidx = 0; var colidx = 0;
foreach (var col in _table.Columns.Values) { foreach (var col in _table.Columns.Values) {
if (colidx > 0) sb.Append(", "); if (colidx > 0) sb.Append(", ");
sb.Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); sb.Append(_commonUtils.QuoteReadColumn(col.CsType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName));
++colidx; ++colidx;
} }
return _orm.Ado.Query<T1>(CommandType.Text, sb.ToString(), _params.ToArray()); return _orm.Ado.Query<T1>(CommandType.Text, sb.ToString(), _params.ToArray());

View File

@ -21,7 +21,7 @@ namespace FreeSql.PostgreSQL.Curd {
var colidx = 0; var colidx = 0;
foreach (var col in _table.Columns.Values) { foreach (var col in _table.Columns.Values) {
if (colidx > 0) sb.Append(", "); if (colidx > 0) sb.Append(", ");
sb.Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); sb.Append(_commonUtils.QuoteReadColumn(col.CsType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName));
++colidx; ++colidx;
} }
return _orm.Ado.Query<T1>(CommandType.Text, sb.ToString(), _params); return _orm.Ado.Query<T1>(CommandType.Text, sb.ToString(), _params);

View File

@ -20,7 +20,7 @@ namespace FreeSql.PostgreSQL.Curd {
var colidx = 0; var colidx = 0;
foreach (var col in _table.Columns.Values) { foreach (var col in _table.Columns.Values) {
if (colidx > 0) sb.Append(", "); if (colidx > 0) sb.Append(", ");
sb.Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); sb.Append(_commonUtils.QuoteReadColumn(col.CsType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName));
++colidx; ++colidx;
} }
return _orm.Ado.Query<T1>(CommandType.Text, sb.ToString(), _params.Concat(_paramsSource).ToArray()); return _orm.Ado.Query<T1>(CommandType.Text, sb.ToString(), _params.Concat(_paramsSource).ToArray());
@ -28,14 +28,14 @@ namespace FreeSql.PostgreSQL.Curd {
protected override void ToSqlCase(StringBuilder caseWhen, ColumnInfo[] primarys) { protected override void ToSqlCase(StringBuilder caseWhen, ColumnInfo[] primarys) {
if (_table.Primarys.Length == 1) { if (_table.Primarys.Length == 1) {
caseWhen.Append(_commonUtils.QuoteSqlName(_table.Primarys.First().Attribute.Name)); caseWhen.Append(_commonUtils.QuoteReadColumn(_table.Primarys.First().CsType, _commonUtils.QuoteSqlName(_table.Primarys.First().Attribute.Name)));
return; return;
} }
caseWhen.Append("("); caseWhen.Append("(");
var pkidx = 0; var pkidx = 0;
foreach (var pk in _table.Primarys) { foreach (var pk in _table.Primarys) {
if (pkidx > 0) caseWhen.Append(" || "); if (pkidx > 0) caseWhen.Append(" || ");
caseWhen.Append(_commonUtils.QuoteSqlName(pk.Attribute.Name)).Append("::varchar"); caseWhen.Append(_commonUtils.QuoteReadColumn(_table.Primarys.First().CsType, _commonUtils.QuoteSqlName(pk.Attribute.Name))).Append("::varchar");
++pkidx; ++pkidx;
} }
caseWhen.Append(")"); caseWhen.Append(")");

View File

@ -39,9 +39,9 @@ namespace FreeSql.PostgreSQL {
{ typeof(long).FullName, (NpgsqlDbType.Bigint, "int8","int8 NOT NULL", false, false, 0) },{ typeof(long?).FullName, (NpgsqlDbType.Bigint, "int8", "int8", false, true, null) }, { typeof(long).FullName, (NpgsqlDbType.Bigint, "int8","int8 NOT NULL", false, false, 0) },{ typeof(long?).FullName, (NpgsqlDbType.Bigint, "int8", "int8", false, true, null) },
{ typeof(byte).FullName, (NpgsqlDbType.Smallint, "int2","int2 NOT NULL", false, false, 0) },{ typeof(byte?).FullName, (NpgsqlDbType.Smallint, "int2", "int2", false, true, null) }, { typeof(byte).FullName, (NpgsqlDbType.Smallint, "int2","int2 NOT NULL", false, false, 0) },{ typeof(byte?).FullName, (NpgsqlDbType.Smallint, "int2", "int2", false, true, null) },
{ typeof(ushort).FullName, (NpgsqlDbType.Smallint, "int2","int2 NOT NULL", false, false, 0) },{ typeof(ushort?).FullName, (NpgsqlDbType.Smallint, "int2", "int2", false, true, null) }, { typeof(ushort).FullName, (NpgsqlDbType.Integer, "int4","int4 NOT NULL", false, false, 0) },{ typeof(ushort?).FullName, (NpgsqlDbType.Integer, "int4", "int4", false, true, null) },
{ typeof(uint).FullName, (NpgsqlDbType.Integer, "int4","int4 NOT NULL", false, false, 0) },{ typeof(uint?).FullName, (NpgsqlDbType.Integer, "int4", "int4", false, true, null) }, { typeof(uint).FullName, (NpgsqlDbType.Bigint, "int8","int8 NOT NULL", false, false, 0) },{ typeof(uint?).FullName, (NpgsqlDbType.Bigint, "int8", "int8", false, true, null) },
{ typeof(ulong).FullName, (NpgsqlDbType.Bigint, "int8","int8 NOT NULL", false, false, 0) },{ typeof(ulong?).FullName, (NpgsqlDbType.Bigint, "int8", "int8", false, true, null) }, { typeof(ulong).FullName, (NpgsqlDbType.Numeric, "numeric","numeric(20,0) NOT NULL", false, false, 0) },{ typeof(ulong?).FullName, (NpgsqlDbType.Numeric, "numeric", "numeric(20,0)", false, true, null) },
{ typeof(float).FullName, (NpgsqlDbType.Real, "float4","float4 NOT NULL", false, false, 0) },{ typeof(float?).FullName, (NpgsqlDbType.Real, "float4", "float4", false, true, null) }, { typeof(float).FullName, (NpgsqlDbType.Real, "float4","float4 NOT NULL", false, false, 0) },{ typeof(float?).FullName, (NpgsqlDbType.Real, "float4", "float4", false, true, null) },
{ typeof(double).FullName, (NpgsqlDbType.Double, "float8","float8 NOT NULL", false, false, 0) },{ typeof(double?).FullName, (NpgsqlDbType.Double, "float8", "float8", false, true, null) }, { typeof(double).FullName, (NpgsqlDbType.Double, "float8","float8 NOT NULL", false, false, 0) },{ typeof(double?).FullName, (NpgsqlDbType.Double, "float8", "float8", false, true, null) },
@ -52,20 +52,20 @@ namespace FreeSql.PostgreSQL {
{ typeof(TimeSpan).FullName, (NpgsqlDbType.Time, "time","time NOT NULL", false, false, 0) },{ typeof(TimeSpan?).FullName, (NpgsqlDbType.Time, "time", "time",false, true, null) }, { typeof(TimeSpan).FullName, (NpgsqlDbType.Time, "time","time NOT NULL", false, false, 0) },{ typeof(TimeSpan?).FullName, (NpgsqlDbType.Time, "time", "time",false, true, null) },
{ typeof(DateTime).FullName, (NpgsqlDbType.Timestamp, "timestamp", "timestamp NOT NULL", false, false, new DateTime(1970,1,1)) },{ typeof(DateTime?).FullName, (NpgsqlDbType.Timestamp, "timestamp", "timestamp", false, true, null) }, { typeof(DateTime).FullName, (NpgsqlDbType.Timestamp, "timestamp", "timestamp NOT NULL", false, false, new DateTime(1970,1,1)) },{ typeof(DateTime?).FullName, (NpgsqlDbType.Timestamp, "timestamp", "timestamp", false, true, null) },
{ typeof(bool).FullName, (NpgsqlDbType.Boolean, "bool","bool NOT NULL", null, false, false) },{ typeof(bool?).FullName, (NpgsqlDbType.Bit, "bool","bool", null, true, null) }, { typeof(bool).FullName, (NpgsqlDbType.Boolean, "bool","bool NOT NULL", null, false, false) },{ typeof(bool?).FullName, (NpgsqlDbType.Boolean, "bool","bool", null, true, null) },
{ typeof(Byte[]).FullName, (NpgsqlDbType.Bytea, "bytea", "bytea", false, null, new byte[0]) }, { typeof(Byte[]).FullName, (NpgsqlDbType.Bytea, "bytea", "bytea", false, null, new byte[0]) },
{ typeof(BitArray).FullName, (NpgsqlDbType.Varbit, "varbit", "varbit(64)", false, null, new BitArray(new byte[64])) }, { typeof(BitArray).FullName, (NpgsqlDbType.Varbit, "varbit", "varbit(64)", false, null, new BitArray(new byte[64])) },
{ typeof(NpgsqlPoint).FullName, (NpgsqlDbType.Point, "point", "point NOT NULL", false, false, new NpgsqlPoint()) },{ typeof(NpgsqlPoint?).FullName, (NpgsqlDbType.Point, "point", "point", false, true, null) }, { typeof(NpgsqlPoint).FullName, (NpgsqlDbType.Point, "point", "point NOT NULL", false, false, new NpgsqlPoint(0, 0)) },{ typeof(NpgsqlPoint?).FullName, (NpgsqlDbType.Point, "point", "point", false, true, null) },
{ typeof(NpgsqlLine).FullName, (NpgsqlDbType.Line, "line", "line NOT NULL", false, false, new NpgsqlLine()) },{ typeof(NpgsqlLine?).FullName, (NpgsqlDbType.Line, "line", "line", false, true, null) }, { typeof(NpgsqlLine).FullName, (NpgsqlDbType.Line, "line", "line NOT NULL", false, false, new NpgsqlLine(0, 0, 1)) },{ typeof(NpgsqlLine?).FullName, (NpgsqlDbType.Line, "line", "line", false, true, null) },
{ typeof(NpgsqlLSeg).FullName, (NpgsqlDbType.LSeg, "lseg", "lseg NOT NULL", false, false, new NpgsqlLSeg()) },{ typeof(NpgsqlLSeg?).FullName, (NpgsqlDbType.LSeg, "lseg", "lseg", false, true, null) }, { typeof(NpgsqlLSeg).FullName, (NpgsqlDbType.LSeg, "lseg", "lseg NOT NULL", false, false, new NpgsqlLSeg(0, 0, 0, 0)) },{ typeof(NpgsqlLSeg?).FullName, (NpgsqlDbType.LSeg, "lseg", "lseg", false, true, null) },
{ typeof(NpgsqlBox).FullName, (NpgsqlDbType.Box, "box", "box NOT NULL", false, false, new NpgsqlBox()) },{ typeof(NpgsqlBox?).FullName, (NpgsqlDbType.Box, "box", "box", false, true, null) }, { typeof(NpgsqlBox).FullName, (NpgsqlDbType.Box, "box", "box NOT NULL", false, false, new NpgsqlBox(0, 0, 0, 0)) },{ typeof(NpgsqlBox?).FullName, (NpgsqlDbType.Box, "box", "box", false, true, null) },
{ typeof(NpgsqlPath).FullName, (NpgsqlDbType.Path, "path", "path NOT NULL", false, false, new NpgsqlPath()) },{ typeof(NpgsqlPath?).FullName, (NpgsqlDbType.Path, "path", "path", false, true, null) }, { typeof(NpgsqlPath).FullName, (NpgsqlDbType.Path, "path", "path NOT NULL", false, false, new NpgsqlPath(new NpgsqlPoint(0, 0))) },{ typeof(NpgsqlPath?).FullName, (NpgsqlDbType.Path, "path", "path", false, true, null) },
{ typeof(NpgsqlPolygon).FullName, (NpgsqlDbType.Polygon, "polygon", "polygon NOT NULL", false, false, new NpgsqlPolygon()) },{ typeof(NpgsqlPolygon?).FullName, (NpgsqlDbType.Polygon, "polygon", "polygon", false, true, null) }, { typeof(NpgsqlPolygon).FullName, (NpgsqlDbType.Polygon, "polygon", "polygon NOT NULL", false, false, new NpgsqlPolygon(new NpgsqlPoint(0, 0), new NpgsqlPoint(0, 0))) },{ typeof(NpgsqlPolygon?).FullName, (NpgsqlDbType.Polygon, "polygon", "polygon", false, true, null) },
{ typeof(NpgsqlCircle).FullName, (NpgsqlDbType.Circle, "circle", "circle NOT NULL", false, false, new NpgsqlCircle()) },{ typeof(NpgsqlCircle?).FullName, (NpgsqlDbType.Circle, "circle", "circle", false, true, null) }, { typeof(NpgsqlCircle).FullName, (NpgsqlDbType.Circle, "circle", "circle NOT NULL", false, false, new NpgsqlCircle(0, 0, 0)) },{ typeof(NpgsqlCircle?).FullName, (NpgsqlDbType.Circle, "circle", "circle", false, true, null) },
{ typeof((IPAddress Address, int Subnet)).FullName, (NpgsqlDbType.Cidr, "cidr", "cidr NOT NULL", false, false, (IPAddress.None, 0)) },{ typeof((IPAddress Address, int Subnet)?).FullName, (NpgsqlDbType.Cidr, "cidr", "cidr", false, true, null) }, { typeof((IPAddress Address, int Subnet)).FullName, (NpgsqlDbType.Cidr, "cidr", "cidr NOT NULL", false, false, (IPAddress.Any, 0)) },{ typeof((IPAddress Address, int Subnet)?).FullName, (NpgsqlDbType.Cidr, "cidr", "cidr", false, true, null) },
{ typeof(IPAddress).FullName, (NpgsqlDbType.Inet, "inet", "inet", false, null, IPAddress.None) }, { typeof(IPAddress).FullName, (NpgsqlDbType.Inet, "inet", "inet", false, null, IPAddress.Any) },
{ typeof(PhysicalAddress).FullName, (NpgsqlDbType.MacAddr, "macaddr", "macaddr", false, null, PhysicalAddress.None) }, { typeof(PhysicalAddress).FullName, (NpgsqlDbType.MacAddr, "macaddr", "macaddr", false, null, PhysicalAddress.None) },
{ typeof(JToken).FullName, (NpgsqlDbType.Jsonb, "jsonb", "jsonb", false, null, JToken.Parse("{}")) }, { typeof(JToken).FullName, (NpgsqlDbType.Jsonb, "jsonb", "jsonb", false, null, JToken.Parse("{}")) },
@ -95,11 +95,12 @@ namespace FreeSql.PostgreSQL {
var info = GetDbInfoNoneArray(elementType); var info = GetDbInfoNoneArray(elementType);
if (info == null) return null; if (info == null) return null;
if (isarray == false) return ((int)info.Value.type, info.Value.dbtype, info.Value.dbtypeFull, info.Value.isnullable, info.Value.defaultValue); if (isarray == false) return ((int)info.Value.type, info.Value.dbtype, info.Value.dbtypeFull, info.Value.isnullable, info.Value.defaultValue);
var dbtypefull = Regex.Replace(info.Value.dbtypeFull, $@"{info.Value.dbtype}(\s*\([^\)]+\))?", "$0[]"); var dbtypefull = Regex.Replace(info.Value.dbtypeFull, $@"{info.Value.dbtype}(\s*\([^\)]+\))?", "$0[]").Replace(" NOT NULL", "");
return ((int)(info.Value.type | NpgsqlDbType.Array), $"{info.Value.dbtype}[]", dbtypefull, info.Value.isnullable, Array.CreateInstance(elementType, 0)); return ((int)(info.Value.type | NpgsqlDbType.Array), $"{info.Value.dbtype}[]", dbtypefull, null, Array.CreateInstance(elementType, 0));
} }
(NpgsqlDbType type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfoNoneArray(Type type) { (NpgsqlDbType type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfoNoneArray(Type type) {
if (_dicCsToDb.TryGetValue(type.FullName, out var trydc)) return new (NpgsqlDbType, string, string, bool?, object)?((trydc.type, trydc.dbtype, trydc.dbtypeFull, trydc.isnullable, trydc.defaultValue)); if (_dicCsToDb.TryGetValue(type.FullName, out var trydc)) return new (NpgsqlDbType, string, string, bool?, object)?((trydc.type, trydc.dbtype, trydc.dbtypeFull, trydc.isnullable, trydc.defaultValue));
if (type.IsArray) return null;
var enumType = type.IsEnum ? type : null; var enumType = type.IsEnum ? type : null;
if (enumType == null && type.FullName.StartsWith("System.Nullable`1[") && type.GenericTypeArguments.Length == 1 && type.GenericTypeArguments.First().IsEnum) enumType = type.GenericTypeArguments.First(); if (enumType == null && type.FullName.StartsWith("System.Nullable`1[") && type.GenericTypeArguments.Length == 1 && type.GenericTypeArguments.First().IsEnum) enumType = type.GenericTypeArguments.First();
if (enumType != null) { if (enumType != null) {

View File

@ -1,10 +1,12 @@
using FreeSql.Internal; using FreeSql.Internal;
using Newtonsoft.Json.Linq;
using Npgsql; using Npgsql;
using NpgsqlTypes; using NpgsqlTypes;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data.Common; using System.Data.Common;
using System.Linq; using System.Linq;
using System.Net;
namespace FreeSql.PostgreSQL { namespace FreeSql.PostgreSQL {
@ -14,39 +16,81 @@ namespace FreeSql.PostgreSQL {
_orm = orm; _orm = orm;
} }
internal override DbParameter AppendParamter(List<DbParameter> _params, string parameterName, object value) { static Array getParamterArrayValue(Type arrayType, object value, object defaultValue) {
var valueArr = value as Array;
var len = valueArr.GetLength(0);
var ret = Array.CreateInstance(arrayType, len);
for (var a = 0; a < len; a++) {
var item = valueArr.GetValue(a);
ret.SetValue(item == null ? defaultValue : getParamterValue(item.GetType(), item, 1), a);
}
return ret;
}
static Dictionary<string, Func<object, object>> dicGetParamterValue = new Dictionary<string, Func<object, object>> {
{ typeof(JToken).FullName, a => string.Concat(a) }, { typeof(JToken[]).FullName, a => getParamterArrayValue(typeof(string), a, null) },
{ typeof(JObject).FullName, a => string.Concat(a) }, { typeof(JObject[]).FullName, a => getParamterArrayValue(typeof(string), a, null) },
{ typeof(JArray).FullName, a => string.Concat(a) }, { typeof(JArray[]).FullName, a => getParamterArrayValue(typeof(string), a, null) },
{ typeof(uint).FullName, a => long.Parse(string.Concat(a)) }, { typeof(uint[]).FullName, a => getParamterArrayValue(typeof(long), a, 0) }, { typeof(uint?[]).FullName, a => getParamterArrayValue(typeof(long?), a, null) },
{ typeof(ulong).FullName, a => decimal.Parse(string.Concat(a)) }, { typeof(ulong[]).FullName, a => getParamterArrayValue(typeof(decimal), a, 0) }, { typeof(ulong?[]).FullName, a => getParamterArrayValue(typeof(decimal?), a, null) },
{ typeof(ushort).FullName, a => int.Parse(string.Concat(a)) }, { typeof(ushort[]).FullName, a => getParamterArrayValue(typeof(int), a, 0) }, { typeof(ushort?[]).FullName, a => getParamterArrayValue(typeof(int?), a, null) },
{ typeof(byte).FullName, a => short.Parse(string.Concat(a)) }, { typeof(byte[]).FullName, a => getParamterArrayValue(typeof(short), a, 0) }, { typeof(byte?[]).FullName, a => getParamterArrayValue(typeof(short?), a, null) },
{ typeof(sbyte).FullName, a => short.Parse(string.Concat(a)) }, { typeof(sbyte[]).FullName, a => getParamterArrayValue(typeof(short), a, 0) }, { typeof(sbyte?[]).FullName, a => getParamterArrayValue(typeof(short?), a, null) },
{ typeof(NpgsqlPath).FullName, a => {
var path = (NpgsqlPath)a;
try { int count = path.Count; return path; } catch { return new NpgsqlPath(new NpgsqlPoint(0, 0)); }
} }, { typeof(NpgsqlPath[]).FullName, a => getParamterArrayValue(typeof(NpgsqlPath), a, new NpgsqlPath(new NpgsqlPoint(0, 0))) }, { typeof(NpgsqlPath?[]).FullName, a => getParamterArrayValue(typeof(NpgsqlPath?), a, null) },
{ typeof(NpgsqlPolygon).FullName, a => {
var polygon = (NpgsqlPolygon)a;
try { int count = polygon.Count; return polygon; } catch { return new NpgsqlPolygon(new NpgsqlPoint(0, 0), new NpgsqlPoint(0, 0)); }
} }, { typeof(NpgsqlPolygon[]).FullName, a => getParamterArrayValue(typeof(NpgsqlPolygon), a, new NpgsqlPolygon(new NpgsqlPoint(0, 0), new NpgsqlPoint(0, 0))) }, { typeof(NpgsqlPolygon?[]).FullName, a => getParamterArrayValue(typeof(NpgsqlPolygon?), a, null) },
{ typeof((IPAddress Address, int Subnet)).FullName, a => {
var inet = ((IPAddress Address, int Subnet))a;
if (inet.Address == null) return (IPAddress.Any, inet.Subnet);
return inet;
} }, { typeof((IPAddress Address, int Subnet)[]).FullName, a => getParamterArrayValue(typeof((IPAddress Address, int Subnet)), a, (IPAddress.Any, 0)) }, { typeof((IPAddress Address, int Subnet)?[]).FullName, a => getParamterArrayValue(typeof((IPAddress Address, int Subnet)?), a, null) },
};
static object getParamterValue(Type type, object value, int level = 0) {
if (type.FullName == "System.Byte[]") return value;
if (type.IsArray && level == 0) {
var elementType = type.GetElementType();
Type enumType = null;
if (elementType.IsEnum) enumType = elementType;
else if (elementType.FullName.StartsWith("System.Nullable`1[") && elementType.GenericTypeArguments.First().IsEnum) enumType = elementType.GenericTypeArguments.First();
if (enumType != null) return enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Any() ?
getParamterArrayValue(typeof(long), value, elementType.IsEnum ? null : Enum.GetValues(enumType).GetValue(0)) :
getParamterArrayValue(typeof(int), value, elementType.IsEnum ? null : Enum.GetValues(enumType).GetValue(0));
return dicGetParamterValue.TryGetValue(type.FullName, out var trydicarr) ? trydicarr(value) : value;
}
if (type.FullName.StartsWith("System.Nullable`1[")) type = type.GenericTypeArguments.First();
if (type.IsEnum) return (int)value;
if (dicGetParamterValue.TryGetValue(type.FullName, out var trydic)) return trydic(value);
return value;
}
internal override DbParameter AppendParamter(List<DbParameter> _params, string parameterName, Type type, object value) {
if (string.IsNullOrEmpty(parameterName)) parameterName = $"p_{_params?.Count}"; if (string.IsNullOrEmpty(parameterName)) parameterName = $"p_{_params?.Count}";
else if (_orm.CodeFirst.IsSyncStructureToLower) parameterName = parameterName.ToLower(); else if (_orm.CodeFirst.IsSyncStructureToLower) parameterName = parameterName.ToLower();
NpgsqlParameter ret = null; if (value != null) value = getParamterValue(type, value);
if (value == null) ret = new NpgsqlParameter { ParameterName = $"{parameterName}", Value = DBNull.Value }; var ret = new NpgsqlParameter { ParameterName = $"@{parameterName}", Value = value };
else { //if (value.GetType().IsEnum || value.GetType().GenericTypeArguments.FirstOrDefault()?.IsEnum == true) {
var type = value.GetType(); // ret.DataTypeName = "";
ret = new NpgsqlParameter { //} else {
ParameterName = parameterName, var tp = _orm.CodeFirst.GetDbInfo(type)?.type;
Value = value if (tp != null) ret.NpgsqlDbType = (NpgsqlDbType)tp.Value;
}; //}
//if (value.GetType().IsEnum || value.GetType().GenericTypeArguments.FirstOrDefault()?.IsEnum == true) {
// ret.DataTypeName = "";
//} else {
var tp = _orm.CodeFirst.GetDbInfo(type)?.type;
if (tp != null) ret.NpgsqlDbType = (NpgsqlDbType)tp.Value;
//}
}
_params?.Add(ret); _params?.Add(ret);
return ret; return ret;
} }
internal override DbParameter[] GetDbParamtersByObject(string sql, object obj) => internal override DbParameter[] GetDbParamtersByObject(string sql, object obj) =>
Utils.GetDbParamtersByObject<NpgsqlParameter>(sql, obj, "@", (name, type, value) => { Utils.GetDbParamtersByObject<NpgsqlParameter>(sql, obj, "@", (name, type, value) => {
var ret = new NpgsqlParameter { if (value != null) value = getParamterValue(type, value);
ParameterName = name, var ret = new NpgsqlParameter { ParameterName = $"@{name}", Value = value };
Value = value ?? DBNull.Value
};
//if (value.GetType().IsEnum || value.GetType().GenericTypeArguments.FirstOrDefault()?.IsEnum == true) { //if (value.GetType().IsEnum || value.GetType().GenericTypeArguments.FirstOrDefault()?.IsEnum == true) {
// ret.DataTypeName = ""; // ret.DataTypeName = "";
//} else { //} else {
var tp = _orm.CodeFirst.GetDbInfo(type)?.type; var tp = _orm.CodeFirst.GetDbInfo(type)?.type;
if (tp != null) ret.NpgsqlDbType = (NpgsqlDbType)tp.Value; if (tp != null) ret.NpgsqlDbType = (NpgsqlDbType)tp.Value;
//} //}
return ret; return ret;
}); });
@ -56,5 +100,8 @@ namespace FreeSql.PostgreSQL {
internal override string QuoteParamterName(string name) => $"@{(_orm.CodeFirst.IsSyncStructureToLower ? name.ToLower() : name)}"; internal override string QuoteParamterName(string name) => $"@{(_orm.CodeFirst.IsSyncStructureToLower ? name.ToLower() : name)}";
internal override string IsNull(string sql, object value) => $"coalesce({sql}, {value})"; internal override string IsNull(string sql, object value) => $"coalesce({sql}, {value})";
internal override string StringConcat(string left, string right, Type leftType, Type rightType) => $"{left} || {right}"; internal override string StringConcat(string left, string right, Type leftType, Type rightType) => $"{left} || {right}";
internal override string QuoteWriteParamter(Type type, string paramterName) => paramterName;
internal override string QuoteReadColumn(Type type, string columnName) => columnName;
} }
} }

View File

@ -20,7 +20,7 @@ namespace FreeSql.SqlServer.Curd {
var colidx = 0; var colidx = 0;
foreach (var col in _table.Columns.Values) { foreach (var col in _table.Columns.Values) {
if (colidx > 0) sb.Append(", "); if (colidx > 0) sb.Append(", ");
sb.Append("DELETED.").Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); sb.Append("DELETED.").Append(_commonUtils.QuoteReadColumn(col.CsType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName));
++colidx; ++colidx;
} }

View File

@ -22,7 +22,7 @@ namespace FreeSql.SqlServer.Curd {
var colidx = 0; var colidx = 0;
foreach (var col in _table.Columns.Values) { foreach (var col in _table.Columns.Values) {
if (colidx > 0) sb.Append(", "); if (colidx > 0) sb.Append(", ");
sb.Append("INSERTED.").Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); sb.Append(_commonUtils.QuoteReadColumn(col.CsType, $"INSERTED.{_commonUtils.QuoteSqlName(col.Attribute.Name)}")).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName));
++colidx; ++colidx;
} }

View File

@ -23,7 +23,7 @@ namespace FreeSql.SqlServer.Curd {
var colidx = 0; var colidx = 0;
foreach (var col in _table.Columns.Values) { foreach (var col in _table.Columns.Values) {
if (colidx > 0) sb.Append(", "); if (colidx > 0) sb.Append(", ");
sb.Append("INSERTED.").Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); sb.Append(_commonUtils.QuoteReadColumn(col.CsType, $"INSERTED.{_commonUtils.QuoteSqlName(col.Attribute.Name)}")).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName));
++colidx; ++colidx;
} }
@ -37,14 +37,14 @@ namespace FreeSql.SqlServer.Curd {
protected override void ToSqlCase(StringBuilder caseWhen, ColumnInfo[] primarys) { protected override void ToSqlCase(StringBuilder caseWhen, ColumnInfo[] primarys) {
if (_table.Primarys.Length == 1) { if (_table.Primarys.Length == 1) {
caseWhen.Append(_commonUtils.QuoteSqlName(_table.Primarys.First().Attribute.Name)); caseWhen.Append(_commonUtils.QuoteReadColumn(_table.Primarys.First().CsType, _commonUtils.QuoteSqlName(_table.Primarys.First().Attribute.Name)));
return; return;
} }
caseWhen.Append("("); caseWhen.Append("(");
var pkidx = 0; var pkidx = 0;
foreach (var pk in _table.Primarys) { foreach (var pk in _table.Primarys) {
if (pkidx > 0) caseWhen.Append(", "); if (pkidx > 0) caseWhen.Append(", ");
caseWhen.Append("cast(").Append(_commonUtils.QuoteSqlName(pk.Attribute.Name)).Append(" as varchar)"); caseWhen.Append("cast(").Append(_commonUtils.QuoteReadColumn(_table.Primarys.First().CsType, _commonUtils.QuoteSqlName(pk.Attribute.Name))).Append(" as varchar)");
++pkidx; ++pkidx;
} }
caseWhen.Append(")"); caseWhen.Append(")");

View File

@ -28,15 +28,15 @@ namespace FreeSql.SqlServer {
static Dictionary<string, (SqlDbType type, string dbtype, string dbtypeFull, bool? isUnsigned, bool? isnullable, object defaultValue)> _dicCsToDb = new Dictionary<string, (SqlDbType type, string dbtype, string dbtypeFull, bool? isUnsigned, bool? isnullable, object defaultValue)>() { static Dictionary<string, (SqlDbType type, string dbtype, string dbtypeFull, bool? isUnsigned, bool? isnullable, object defaultValue)> _dicCsToDb = new Dictionary<string, (SqlDbType type, string dbtype, string dbtypeFull, bool? isUnsigned, bool? isnullable, object defaultValue)>() {
{ typeof(bool).FullName, (SqlDbType.Bit, "bit","bit NOT NULL", null, false, false) },{ typeof(bool?).FullName, (SqlDbType.Bit, "bit","bit", null, true, null) }, { typeof(bool).FullName, (SqlDbType.Bit, "bit","bit NOT NULL", null, false, false) },{ typeof(bool?).FullName, (SqlDbType.Bit, "bit","bit", null, true, null) },
{ typeof(sbyte).FullName, (SqlDbType.TinyInt, "tinyint", "tinyint NOT NULL", false, false, 0) },{ typeof(sbyte?).FullName, (SqlDbType.TinyInt, "tinyint", "tinyint", false, true, null) }, { typeof(sbyte).FullName, (SqlDbType.SmallInt, "smallint", "smallint NOT NULL", false, false, 0) },{ typeof(sbyte?).FullName, (SqlDbType.SmallInt, "smallint", "smallint", false, true, null) },
{ typeof(short).FullName, (SqlDbType.SmallInt, "smallint","smallint NOT NULL", false, false, 0) },{ typeof(short?).FullName, (SqlDbType.SmallInt, "smallint", "smallint", false, true, null) }, { typeof(short).FullName, (SqlDbType.SmallInt, "smallint","smallint NOT NULL", false, false, 0) },{ typeof(short?).FullName, (SqlDbType.SmallInt, "smallint", "smallint", false, true, null) },
{ typeof(int).FullName, (SqlDbType.Int, "int", "int NOT NULL", false, false, 0) },{ typeof(int?).FullName, (SqlDbType.Int, "int", "int", false, true, null) }, { typeof(int).FullName, (SqlDbType.Int, "int", "int NOT NULL", false, false, 0) },{ typeof(int?).FullName, (SqlDbType.Int, "int", "int", false, true, null) },
{ typeof(long).FullName, (SqlDbType.BigInt, "bigint","bigint NOT NULL", false, false, 0) },{ typeof(long?).FullName, (SqlDbType.BigInt, "bigint","bigint", false, true, null) }, { typeof(long).FullName, (SqlDbType.BigInt, "bigint","bigint NOT NULL", false, false, 0) },{ typeof(long?).FullName, (SqlDbType.BigInt, "bigint","bigint", false, true, null) },
{ typeof(byte).FullName, (SqlDbType.TinyInt, "tinyint","tinyint NOT NULL", true, false, 0) },{ typeof(byte?).FullName, (SqlDbType.TinyInt, "tinyint","tinyint", true, true, null) }, { typeof(byte).FullName, (SqlDbType.TinyInt, "tinyint","tinyint NOT NULL", true, false, 0) },{ typeof(byte?).FullName, (SqlDbType.TinyInt, "tinyint","tinyint", true, true, null) },
{ typeof(ushort).FullName, (SqlDbType.SmallInt, "smallint","smallint NOT NULL", true, false, 0) },{ typeof(ushort?).FullName, (SqlDbType.SmallInt, "smallint", "smallint", true, true, null) }, { typeof(ushort).FullName, (SqlDbType.Int, "int","int NOT NULL", true, false, 0) },{ typeof(ushort?).FullName, (SqlDbType.Int, "int", "int", true, true, null) },
{ typeof(uint).FullName, (SqlDbType.Int, "int", "int NOT NULL", true, false, 0) },{ typeof(uint?).FullName, (SqlDbType.Int, "int", "int", true, true, null) }, { typeof(uint).FullName, (SqlDbType.BigInt, "bigint", "bigint NOT NULL", true, false, 0) },{ typeof(uint?).FullName, (SqlDbType.BigInt, "bigint", "bigint", true, true, null) },
{ typeof(ulong).FullName, (SqlDbType.BigInt, "bigint", "bigint NOT NULL", true, false, 0) },{ typeof(ulong?).FullName, (SqlDbType.BigInt, "bigint", "bigint", true, true, null) }, { typeof(ulong).FullName, (SqlDbType.Decimal, "decimal", "decimal(20,0) NOT NULL", true, false, 0) },{ typeof(ulong?).FullName, (SqlDbType.Decimal, "decimal", "decimal(20,0)", true, true, null) },
{ typeof(double).FullName, (SqlDbType.Float, "float", "float NOT NULL", false, false, 0) },{ typeof(double?).FullName, (SqlDbType.Float, "float", "float", false, true, null) }, { typeof(double).FullName, (SqlDbType.Float, "float", "float NOT NULL", false, false, 0) },{ typeof(double?).FullName, (SqlDbType.Float, "float", "float", false, true, null) },
{ typeof(float).FullName, (SqlDbType.Real, "real","real NOT NULL", false, false, 0) },{ typeof(float?).FullName, (SqlDbType.Real, "real","real", false, true, null) }, { typeof(float).FullName, (SqlDbType.Real, "real","real NOT NULL", false, false, 0) },{ typeof(float?).FullName, (SqlDbType.Real, "real","real", false, true, null) },
@ -54,6 +54,7 @@ namespace FreeSql.SqlServer {
public (int type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfo(Type type) { public (int type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfo(Type type) {
if (_dicCsToDb.TryGetValue(type.FullName, out var trydc)) return new (int, string, string, bool?, object)?(((int)trydc.type, trydc.dbtype, trydc.dbtypeFull, trydc.isnullable, trydc.defaultValue)); if (_dicCsToDb.TryGetValue(type.FullName, out var trydc)) return new (int, string, string, bool?, object)?(((int)trydc.type, trydc.dbtype, trydc.dbtypeFull, trydc.isnullable, trydc.defaultValue));
if (type.IsArray) return null;
var enumType = type.IsEnum ? type : null; var enumType = type.IsEnum ? type : null;
if (enumType == null && type.FullName.StartsWith("System.Nullable`1[") && type.GenericTypeArguments.Length == 1 && type.GenericTypeArguments.First().IsEnum) enumType = type.GenericTypeArguments.First(); if (enumType == null && type.FullName.StartsWith("System.Nullable`1[") && type.GenericTypeArguments.Length == 1 && type.GenericTypeArguments.First().IsEnum) enumType = type.GenericTypeArguments.First();
if (enumType != null) { if (enumType != null) {

View File

@ -13,33 +13,24 @@ namespace FreeSql.SqlServer {
_orm = mysql; _orm = mysql;
} }
internal override DbParameter AppendParamter(List<DbParameter> _params, string parameterName, object value) { internal override DbParameter AppendParamter(List<DbParameter> _params, string parameterName, Type type, object value) {
if (string.IsNullOrEmpty(parameterName)) parameterName = $"p_{_params?.Count}"; if (string.IsNullOrEmpty(parameterName)) parameterName = $"p_{_params?.Count}";
else if (_orm.CodeFirst.IsSyncStructureToLower) parameterName = parameterName.ToLower(); else if (_orm.CodeFirst.IsSyncStructureToLower) parameterName = parameterName.ToLower();
SqlParameter ret = null; if (value?.Equals(DateTime.MinValue) == true) value = new DateTime(1970, 1, 1);
if (value == null) ret = new SqlParameter { ParameterName = $"{parameterName}", Value = DBNull.Value }; var ret = new SqlParameter { ParameterName = $"@{parameterName}", Value = value };
else { var tp = _orm.CodeFirst.GetDbInfo(type)?.type;
var type = value.GetType(); if (tp != null) ret.SqlDbType = (SqlDbType)tp.Value;
ret = new SqlParameter {
ParameterName = parameterName,
Value = value
};
var tp = _orm.CodeFirst.GetDbInfo(type)?.type;
if (tp != null) ret.SqlDbType = (SqlDbType)tp.Value;
}
_params?.Add(ret); _params?.Add(ret);
return ret; return ret;
} }
internal override DbParameter[] GetDbParamtersByObject(string sql, object obj) => internal override DbParameter[] GetDbParamtersByObject(string sql, object obj) =>
Utils.GetDbParamtersByObject<SqlParameter>(sql, obj, "@", (name, type, value) => { Utils.GetDbParamtersByObject<SqlParameter>(sql, obj, "@", (name, type, value) => {
var cp = new SqlParameter { if (value?.Equals(DateTime.MinValue) == true) value = new DateTime(1970, 1, 1);
ParameterName = name, var ret = new SqlParameter { ParameterName = $"@{name}", Value = value };
Value = value ?? DBNull.Value
};
var tp = _orm.CodeFirst.GetDbInfo(type)?.type; var tp = _orm.CodeFirst.GetDbInfo(type)?.type;
if (tp != null) cp.SqlDbType = (SqlDbType)tp.Value; if (tp != null) ret.SqlDbType = (SqlDbType)tp.Value;
return cp; return ret;
}); });
internal override string FormatSql(string sql, params object[] args) => sql?.FormatSqlServer(args); internal override string FormatSql(string sql, params object[] args) => sql?.FormatSqlServer(args);
@ -47,5 +38,8 @@ namespace FreeSql.SqlServer {
internal override string QuoteParamterName(string name) => $"@{(_orm.CodeFirst.IsSyncStructureToLower ? name.ToLower() : name)}"; internal override string QuoteParamterName(string name) => $"@{(_orm.CodeFirst.IsSyncStructureToLower ? name.ToLower() : name)}";
internal override string IsNull(string sql, object value) => $"isnull({sql}, {value})"; internal override string IsNull(string sql, object value) => $"isnull({sql}, {value})";
internal override string StringConcat(string left, string right, Type leftType, Type rightType) => $"{(leftType.FullName == "System.String" ? left : $"cast({left} as nvarchar)")} + {(rightType.FullName == "System.String" ? right : $"cast({right} as nvarchar)")}"; internal override string StringConcat(string left, string right, Type leftType, Type rightType) => $"{(leftType.FullName == "System.String" ? left : $"cast({left} as nvarchar)")} + {(rightType.FullName == "System.String" ? right : $"cast({right} as nvarchar)")}";
internal override string QuoteWriteParamter(Type type, string paramterName) => paramterName;
internal override string QuoteReadColumn(Type type, string columnName) => columnName;
} }
} }