
Imports System.Text
Imports UTS_Core.Database

Namespace UTSModule.Test.Command.SystemCommand

    ''' <summary>
    ''' 对数据库进行执行操作，用于查询单个字段内容
    ''' </summary>
    Public Class GetDBDataExecutor
        Inherits TestCommandExecutor

        Private _searchType As String
        Private _dbName As String
        Private _tbName As String
        Private _colNames As String
        Private _condition As String


        Sub New(command As TestCommand)
            MyBase.New(command)
            _searchType = command.Parameter(0)
            _dbName = command.Parameter(1)
            _tbName = command.Parameter(2)
            _colNames = command.Parameter(3)
            _condition = command.Parameter(4)

        End Sub

        Public Overrides Function Execute() As TestCommandReturn
            Dim db As DbExecutor

            Select Case _searchType
                Case "1"
                    db = New DbExecutor(UtsDb.RemoteDbType, UtsDb.RemoteConnString)
                Case Else
                    db = New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
            End Select

            'todo:此处有Sql注入的风险，应改为插值查询
            Dim cmd As New StringBuilder
            cmd.Append($"Select {_colNames} From ")
            If String.IsNullOrEmpty(_dbName) = False Then
                cmd.Append($" {_dbName}.")
            End If
            cmd.Append($"{_tbName}")

            If String.IsNullOrWhiteSpace(_condition) = False Then
                cmd.Append($" WHERE {_condition}")
            End If
            cmd.Append(";")

            '执行查询
            Try
                db.Open()

                ' db.AddDbParameter(DbType.AnsiString, "colNames", _colNames)
                'db.AddDbParameter(DbType.AnsiString, "dbName", _dbName)
                ' db.AddDbParameter(DbType.AnsiString, "tbName", _tbName)
                'db.AddDbParameter(DbType.AnsiString, "condition", _condition)

                Dim scalar As Object = db.ExecuteScalar(cmd.ToString)
                If scalar Is Nothing Then
                    CommandReturn.ExecuteResult = False
                    CommandReturn.RecordValue = ""
                    CommandReturn.ExecuteResultTipString = "查询数据成功,返回值为空"
                Else
                    CommandReturn.ExecuteResult = True
                    CommandReturn.RecordValue = scalar.ToString
                    CommandReturn.ExecuteResultTipString = "查询数据成功"
                End If

                db.ClearDbParameter()

                db.Close()
            Catch ex As Exception
                CommandReturn.ExecuteResult = False
                CommandReturn.RecordValue = String.Empty
                CommandReturn.ExecuteResultTipString = ex.Message
            End Try

            '回收连接
            Try
                db.Dispose()
            Catch ex As Exception

            End Try

            Return CommandReturn
        End Function
    End Class
End Namespace
