解剖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 ; }
} public object GetValue(byte[] value)
{
if (value.Length != )
throw new ArgumentException("Invalid value length: " + value.Length); return BitConverter.ToInt32(value, );
}
}
相关测试
[TestFixture]
public class SqlIntTests
{
[Test]
public void GetValue()
{
var type = new SqlInt();
byte[] input; input = new byte[] { 0x5e, 0x3b, 0x27, 0x2a };
Assert.AreEqual(, Convert.ToInt32(type.GetValue(input))); input = new byte[] { 0x8d, 0xf9, 0xaa, 0x30 };
Assert.AreEqual(, Convert.ToInt32(type.GetValue(input))); input = new byte[] { 0x7a, 0x4a, 0x72, 0xe2 };
Assert.AreEqual(-, Convert.ToInt32(type.GetValue(input)));
} [Test]
public void Length()
{
var type = new SqlInt(); Assert.Throws<ArgumentException>(() => type.GetValue(new byte[]));
Assert.Throws<ArgumentException>(() => type.GetValue(new byte[]));
}
}
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类型,因为这两个类型相比起其他类型有些特殊
其余类型我以后也将会进行实现
第三篇完