解剖SQLSERVER 第三篇 数据类型的实现(译)
解剖SQLSERVER 第三篇 数据类型的实现(译)
http://improve.dk/implementing-data-types-in-orcamdf/
实现对SQLSERVER数据类型的解析在OrcaMDF 软件里面是一件比较简单的事,只需要实现ISqlType 接口
public interface ISqlType { bool IsVariableLength { get; } short? FixedLength { get; } object GetValue(byte[] value); }
IsVariableLength 返回数据类型是否是定长的还是变长的。
FixedLength 返回定长数据类型的长度,否则他返回null
数据类型解释器不关心变长字段的长度,输入的字节大小会决定长度
最后,GetValue 将输入字节参数进行解释并将字节解释为相关的.NET对象
SqlInt实现
int类型作为定长类型是非常简单的,能直接使用BitConverter进行转换
public class SqlInt : ISqlType { public bool IsVariableLength { get { return false; } } public short? FixedLength { get { return 4; } } public object GetValue(byte[] value) { if (value.Length != 4) throw new ArgumentException("Invalid value length: " + value.Length); return BitConverter.ToInt32(value, 0); } }
相关测试
[TestFixture] public class SqlIntTests { [Test] public void GetValue() { var type = new SqlInt(); byte[] input; input = new byte[] { 0x5e, 0x3b, 0x27, 0x2a }; Assert.AreEqual(707214174, Convert.ToInt32(type.GetValue(input))); input = new byte[] { 0x8d, 0xf9, 0xaa, 0x30 }; Assert.AreEqual(816511373, Convert.ToInt32(type.GetValue(input))); input = new byte[] { 0x7a, 0x4a, 0x72, 0xe2 }; Assert.AreEqual(-495826310, Convert.ToInt32(type.GetValue(input))); } [Test] public void Length() { var type = new SqlInt(); Assert.Throws<ArgumentException>(() => type.GetValue(new byte[3])); Assert.Throws<ArgumentException>(() => type.GetValue(new byte[5])); } }
SqlNVarchar 实现
nvarchar 类型也是非常简单的,注意,如果是可变长度我们返回长度的结果是null
ISqlType 接口实现必须是无状态的
GetValue 简单的将输入的字节的数进行转换,这将转换为相关的.NET 类型,这里是string类型
public class SqlNVarchar : ISqlType { public bool IsVariableLength { get { return true; } } public short? FixedLength { get { return null; } } public object GetValue(byte[] value) { return Encoding.Unicode.GetString(value); } }
相关测试
[TestFixture] public class SqlNvarcharTests { [Test] public void GetValue() { var type = new SqlNVarchar(); byte[] input = new byte[] { 0x47, 0x04, 0x2f, 0x04, 0xe6, 0x00 }; Assert.AreEqual("u0447u042fu00e6", (string)type.GetValue(input)); } }
其他类型的实现
OrcaMDF 软件现在支持12种数据类型,以后将会支持datetime和bit类型,因为这两个类型相比起其他类型有些特殊
其余类型我以后也将会进行实现
第三篇完
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)