Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

5.2 KB
Raw Blame
use super::{AllHeaderTy, Encode, ALL_HEADERS_LEN_TX};
use crate::{tds::codec::ColumnData, BytesMutWithTypeInfo, Result};
use bytes::{BufMut, BytesMut};
use enumflags2::{bitflags, BitFlags};
use std::borrow::BorrowMut;
use std::borrow::Cow;

#[bitflags]
#[repr(u8)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum RpcStatus {
    ByRefValue = 1 << 0,
    DefaultValue = 1 << 1,
    // reserved
    Encrypted = 1 << 3,
}

#[bitflags]
#[repr(u16)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum RpcOption {
    WithRecomp = 1 << 0,
    NoMeta = 1 << 1,
    ReuseMeta = 1 << 2,
}

#[derive(Debug)]
pub struct TokenRpcRequest<'a> {
    proc_id: RpcProcIdValue<'a>,
    flags: BitFlags<RpcOption>,
    params: Vec<RpcParam<'a>>,
    transaction_desc: [u8; 8],
    tds_version: crate::FeatureLevel,
}

impl<'a> TokenRpcRequest<'a> {
    pub fn new<I>(proc_id: I, params: Vec<RpcParam<'a>>, transaction_desc: [u8; 8]) -> Self
    where
        I: Into<RpcProcIdValue<'a>>,
    {
        Self {
            proc_id: proc_id.into(),
            flags: BitFlags::empty(),
            params,
            transaction_desc,
            tds_version: crate::FeatureLevel::default(),
        }
    }
    pub fn with_tds_version(mut self, version: crate::FeatureLevel) -> Self {
        self.tds_version = version;
        self
    }
}

#[derive(Debug)]
pub struct RpcParam<'a> {
    pub name: Cow<'a, str>,
    pub flags: BitFlags<RpcStatus>,
    pub value: ColumnData<'a>,
}

/// 2.2.6.6 RPC Request
#[allow(dead_code)]
#[repr(u8)]
#[derive(Clone, Copy, Debug)]
pub enum RpcProcId {
    CursorOpen = 2,
    CursorFetch = 7,
    CursorClose = 9,
    ExecuteSQL = 10,
    Prepare = 11,
    Execute = 12,
    PrepExec = 13,
    Unprepare = 15,
}

#[derive(Debug)]
#[allow(dead_code)]
pub enum RpcProcIdValue<'a> {
    Name(Cow<'a, str>),
    Id(RpcProcId),
}

impl<'a, S> From<S> for RpcProcIdValue<'a>
where
    S: Into<Cow<'a, str>>,
{
    fn from(s: S) -> Self {
        Self::Name(s.into())
    }
}

impl<'a> From<RpcProcId> for RpcProcIdValue<'a> {
    fn from(id: RpcProcId) -> Self {
        Self::Id(id)
    }
}

impl<'a> Encode<BytesMut> for TokenRpcRequest<'a> {
    fn encode(self, dst: &mut BytesMut) -> Result<()> {
        if self.tds_version >= crate::FeatureLevel::SqlServer2005 {
            dst.put_u32_le(ALL_HEADERS_LEN_TX as u32);
            dst.put_u32_le(ALL_HEADERS_LEN_TX as u32 - 4);
            dst.put_u16_le(AllHeaderTy::TransactionDescriptor as u16);
            dst.put_slice(&self.transaction_desc);
            dst.put_u32_le(1);
        }

        match self.proc_id {
            RpcProcIdValue::Id(ref id) => {
                let val = (0xffff_u32) | ((*id as u16) as u32) << 16;
                dst.put_u32_le(val);
            }
            RpcProcIdValue::Name(ref _name) => {
                //let (left_bytes, _) = try!(write_varchar::<u16>(&mut cursor, name, 0));
                //assert_eq!(left_bytes, 0);
                todo!()
            }
        }

        dst.put_u16_le(self.flags.bits());

        for param in self.params.into_iter() {
            param.encode_for_version(dst, self.tds_version)?;
        }

        Ok(())
    }
}

impl<'a> Encode<BytesMut> for RpcParam<'a> {
    fn encode(self, dst: &mut BytesMut) -> Result<()> {
        self.encode_for_version(dst, crate::FeatureLevel::default())
    }
}
impl<'a> RpcParam<'a> {
    fn encode_for_version(self, dst: &mut BytesMut, version: crate::FeatureLevel) -> Result<()> {
        let len_pos = dst.len();
        let mut length = 0u8;

        dst.put_u8(length);

        for codepoint in self.name.encode_utf16() {
            length += 1;
            dst.put_u16_le(codepoint);
        }

        dst.put_u8(self.flags.bits());

        let legacy_lob = if version < crate::FeatureLevel::SqlServer2005 {
            match &self.value {
                ColumnData::String(Some(s)) if s.encode_utf16().count() > 4000 => {
                    let units = u32::try_from(s.encode_utf16().count()).map_err(|_| crate::Error::Protocol("NTEXT parameter too large".into()))?;
                    let bytes = units.checked_mul(2).ok_or_else(|| crate::Error::Protocol("NTEXT parameter too large".into()))?;
                    dst.put_u8(0x63); // NTEXT TYPE_INFO, followed by L_VARBYTE
                    dst.put_u32_le(bytes);
                    dst.extend_from_slice(&[0; 5]); // default collation
                    dst.put_u32_le(bytes);
                    for unit in s.encode_utf16() { dst.put_u16_le(unit); }
                    true
                }
                ColumnData::Binary(Some(b)) if b.len() > 8000 => {
                    let len = u32::try_from(b.len()).map_err(|_| crate::Error::Protocol("IMAGE parameter too large".into()))?;
                    dst.put_u8(0x22); // IMAGE TYPE_INFO, followed by L_VARBYTE
                    dst.put_u32_le(len); dst.put_u32_le(len); dst.extend_from_slice(b);
                    true
                }
                _ => false,
            }
        } else { false };
        if !legacy_lob {
            let mut dst_fi = BytesMutWithTypeInfo::new(dst);
            self.value.encode(&mut dst_fi)?;
        }

        let dst: &mut [u8] = dst.borrow_mut();
        dst[len_pos] = length;

        Ok(())
    }
}