文章出處

解剖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類型,因為這兩個類型相比起其他類型有些特殊

其余類型我以后也將會進行實現

 

第三篇完


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()