解剖sqlserver 第三篇 数据类型的实现(译) http://improve.dk/implementing-data-types-in-orcamdf/ 实现对sqlserver数据类型的解析在orcamdf 软件里面是一件比较简单的事,只需要实现isqltype 接口 public interface isqltype{ bool isvariablelength { g
解剖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(() => type.getvalue(new byte[3])); assert.throws(() => 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类型,因为这两个类型相比起其他类型有些特殊
其余类型我以后也将会进行实现
第三篇完