App.jsx 18.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
import React, { useState, useRef, useCallback } from 'react'
import { Button, message, Tag, Space, Tooltip } from 'antd'
import {
  DatabaseOutlined,
  PlayCircleOutlined,
  SafetyCertificateOutlined,
  FormatPainterOutlined,
  SearchOutlined,
  SettingOutlined,
  LeftOutlined,
  RightOutlined,
  FolderOutlined,
  MailOutlined,
} from '@ant-design/icons'
import { format as sqlFormat } from 'sql-formatter'
import dayjs from 'dayjs'
import ConnectionModal from './components/ConnectionModal'
import SqlEditor from './components/SqlEditor'
import ConditionModal, { extractVariables, buildSqlWithDateRange, parseVariables } from './components/ConditionPanel'
import ExecutionCheckModal from './components/ExecutionCheckModal'
import ErrorReportModal from './components/ErrorReportModal'
import SqlManagerModal from './components/SqlManagerModal'
import SmtpConfigModal from './components/SmtpConfigModal'
import ResultTable from './components/ResultTable'
import request from './utils/request'

// 前端SQL类型检测(与后端 sql-analyzer.js 保持一致)
const BLOCKED_SQL_TYPES = ['INSERT', 'UPDATE', 'DELETE', 'REPLACE', 'CREATE', 'ALTER', 'DROP', 'TRUNCATE', 'LOAD DATA', 'CALL', 'GRANT', 'REVOKE']

function detectSqlTypeFrontend(sql) {
  if (!sql || !sql.trim()) return { type: 'EMPTY', isSelect: true }
  const cleaned = sql.replace(/--[^\n]*/g, ' ').replace(/#[^\n]*/g, ' ').replace(/\/\*[\s\S]*?\*\//g, ' ').trim()
  const upper = cleaned.toUpperCase()
  if (/^\s*SELECT\b/.test(upper)) return { type: 'SELECT', isSelect: true }
  if (/^\s*WITH\b/.test(upper)) return { type: 'SELECT', isSelect: true }
  for (const kw of BLOCKED_SQL_TYPES) {
    const regex = new RegExp(`^\\s*${kw.replace(/\s+/g, '\\s+')}\\b`, 'i')
    if (regex.test(upper)) return { type: kw.replace(/\s+/g, '_'), isSelect: false, label: kw }
  }
  return { type: 'OTHER', isSelect: false, label: '未知类型' }
}

function validateSelectOnlyFrontend(sql) {
  if (!sql || !sql.trim()) return { allowed: true, reason: null }
  const stmts = sql.split(';').filter(s => s.trim())
  for (let i = 0; i < stmts.length; i++) {
    const det = detectSqlTypeFrontend(stmts[i])
    if (!det.isSelect) {
      return { allowed: false, reason: `仅允许SELECT查询语句,检测到第${i + 1}条语句为 ${det.label},不允许执行` }
    }
  }
  return { allowed: true, reason: null }
}

// 清空右侧查询结果
function clearQueryResults(setQueryId, setResultColumns, setResultTotal, setResultDuration) {
  setQueryId(null)
  setResultColumns([])
  setResultTotal(0)
  setResultDuration(null)
}

export default function App() {
  // 数据库连接状态
  const [connId, setConnId] = useState(null)
  const [connInfo, setConnInfo] = useState(null)
  const [connModalOpen, setConnModalOpen] = useState(false)

  // SQL编辑器
  const [sqlText, setSqlText] = useState('')

  // 条件配置 - 改为弹层
  const [conditions, setConditions] = useState([])
  const [condModalOpen, setCondModalOpen] = useState(false)

  // 执行检查
  const [checkModalOpen, setCheckModalOpen] = useState(false)
  const [checkResult, setCheckResult] = useState(null)
  const [finalSql, setFinalSql] = useState('')

  // 执行结果
  const [execLoading, setExecLoading] = useState(false)
  const [queryId, setQueryId] = useState(null)
  const [resultColumns, setResultColumns] = useState([])
  const [resultTotal, setResultTotal] = useState(0)
  const [resultDuration, setResultDuration] = useState(null)

  // 错误报告
  const [errorModalOpen, setErrorModalOpen] = useState(false)
  const [errorInfo, setErrorInfo] = useState(null)

  // SQL管理
  const [sqlManagerOpen, setSqlManagerOpen] = useState(false)
  const [currentScriptId, setCurrentScriptId] = useState(null)  // 当前加载的脚本ID

  // SMTP配置(全局)
  const [smtpConfigOpen, setSmtpConfigOpen] = useState(false)

  // 可拖动面板 - 左侧面板宽度 & 折叠状态
  const [leftWidth, setLeftWidth] = useState(55) // 百分比
  const [leftCollapsed, setLeftCollapsed] = useState(false)
  const dragging = useRef(false)
  const startX = useRef(0)
  const startWidth = useRef(0)

  // 显示错误报告
  const showError = (errorMsg, sql, phase) => {
    setErrorInfo({
      error: errorMsg,
      sql: sql || finalSql || sqlText,
      phase: phase || '执行阶段',
      timestamp: new Date().toLocaleString(),
    })
    setErrorModalOpen(true)
  }

  // 连接数据库
  const handleConnect = (conn) => {
    setConnId(conn.id)
    setConnInfo(conn)
    message.success(`已连接: ${conn.name}`)
  }

  // 构建最终SQL(替换条件占位符)
  const buildFinalSql = () => {
    let sql = sqlText
    if (conditions.length > 0) {
      sql = buildSqlWithDateRange(sqlText, conditions)
    }
    return sql
  }

  // SQL格式化
  const handleFormatSql = () => {
    if (!sqlText.trim()) return
    try {
      const formatted = sqlFormat(sqlText, {
        language: 'sql',
        tabWidth: 2,
        keywordCase: 'upper',
        linesBetweenQueries: 2,
      })
      setSqlText(formatted)
      message.success('SQL格式化完成')
    } catch (e) {
      message.error('格式化失败:' + e.message)
    }
  }

  // 解析条件
  const handleParseConditions = () => {
    const vars = extractVariables(sqlText)
    if (vars.length === 0) {
      message.info('未在SQL中发现 {{变量名}} 占位符')
      return
    }
    const newConds = parseVariables(sqlText, conditions)
    setConditions(newConds)
    setCondModalOpen(true)
    message.success(`解析到 ${vars.length} 个条件参数`)
  }

  // 预检查
  const handleCheck = async () => {
    if (!connId) {
      message.warning('请先连接数据库')
      setConnModalOpen(true)
      return
    }
    if (!sqlText.trim()) {
      message.warning('请输入SQL语句')
      return
    }

    const sql = buildFinalSql()

    // 校验SQL必须为SELECT语句
    const sqlCheck = validateSelectOnlyFrontend(sql)
    if (!sqlCheck.allowed) {
      clearQueryResults(setQueryId, setResultColumns, setResultTotal, setResultDuration)
      showError(sqlCheck.reason, sql, 'SQL校验')
      return
    }

    setFinalSql(sql)

    try {
      const res = await request.post('/query/check', { connId, sql })
      if (res.success) {
        setCheckResult(res.data)
        setCheckModalOpen(true)
      } else {
        clearQueryResults(setQueryId, setResultColumns, setResultTotal, setResultDuration)
        showError(res.message, sql, '预检查阶段')
      }
    } catch (e) {
      clearQueryResults(setQueryId, setResultColumns, setResultTotal, setResultDuration)
      showError(e.message || '检查失败', sql, '预检查阶段')
    }
  }

  // 确认执行
  const handleConfirmExecute = async () => {
    setCheckModalOpen(false)

    // 校验SQL必须为SELECT语句(双保险)
    const sqlCheck = validateSelectOnlyFrontend(finalSql)
    if (!sqlCheck.allowed) {
      clearQueryResults(setQueryId, setResultColumns, setResultTotal, setResultDuration)
      showError(sqlCheck.reason, finalSql, 'SQL校验')
      return
    }

    setExecLoading(true)

    try {
      const res = await request.post('/query/execute', { connId, sql: finalSql })
      if (res.success) {
        const { queryId, isResultSet, columns, totalCount, duration, affectedRows, message: msg } = res.data
        if (isResultSet) {
          setQueryId(queryId)
          setResultColumns(columns)
          setResultTotal(totalCount)
          setResultDuration(duration)
          message.success(`查询完成,共 ${totalCount} 条,耗时 ${(duration / 1000).toFixed(2)}s`)
        } else {
          message.success(msg || `执行成功,影响 ${affectedRows} 行`)
        }
        // 执行成功后自动同步参数到脚本
        syncConditionsToScript()
      } else {
        clearQueryResults(setQueryId, setResultColumns, setResultTotal, setResultDuration)
        showError(res.message, finalSql, '确认执行阶段')
      }
    } catch (e) {
      clearQueryResults(setQueryId, setResultColumns, setResultTotal, setResultDuration)
      showError(e.message || '执行失败', finalSql, '确认执行阶段')
    } finally {
      setExecLoading(false)
    }
  }
  const handleDirectExecute = async () => {
    if (!connId) {
      message.warning('请先连接数据库')
      setConnModalOpen(true)
      return
    }
    if (!sqlText.trim()) {
      message.warning('请输入SQL语句')
      return
    }

    const sql = buildFinalSql()

    // 校验SQL必须为SELECT语句
    const sqlCheck = validateSelectOnlyFrontend(sql)
    if (!sqlCheck.allowed) {
      clearQueryResults(setQueryId, setResultColumns, setResultTotal, setResultDuration)
      showError(sqlCheck.reason, sql, 'SQL校验')
      return
    }

    setFinalSql(sql)
    setExecLoading(true)

    try {
      const res = await request.post('/query/execute', { connId, sql })
      if (res.success) {
        const { queryId, isResultSet, columns, totalCount, duration, affectedRows, message: msg } = res.data
        if (isResultSet) {
          setQueryId(queryId)
          setResultColumns(columns)
          setResultTotal(totalCount)
          setResultDuration(duration)
          message.success(`查询完成,共 ${totalCount} 条,耗时 ${(duration / 1000).toFixed(2)}s`)
        } else {
          message.success(msg || `执行成功,影响 ${affectedRows} 行`)
        }
        // 执行成功后自动同步参数到脚本
        syncConditionsToScript()
      } else {
        clearQueryResults(setQueryId, setResultColumns, setResultTotal, setResultDuration)
        showError(res.message, sql, '执行阶段')
      }
    } catch (e) {
      clearQueryResults(setQueryId, setResultColumns, setResultTotal, setResultDuration)
      showError(e.message || '执行失败', sql, '执行阶段')
    } finally {
      setExecLoading(false)
    }
  }
  const handleMouseDown = useCallback((e) => {
    e.preventDefault()
    dragging.current = true
    startX.current = e.clientX
    startWidth.current = leftWidth
    document.body.style.cursor = 'col-resize'
    document.body.style.userSelect = 'none'

    const handleMouseMove = (e) => {
      if (!dragging.current) return
      const bodyWidth = document.body.offsetWidth
      const dx = e.clientX - startX.current
      const percent = startWidth.current + (dx / bodyWidth) * 100
      const clamped = Math.max(15, Math.min(85, percent))
      setLeftWidth(clamped)
    }

    const handleMouseUp = () => {
      dragging.current = false
      document.body.style.cursor = ''
      document.body.style.userSelect = ''
      document.removeEventListener('mousemove', handleMouseMove)
      document.removeEventListener('mouseup', handleMouseUp)
    }

    document.addEventListener('mousemove', handleMouseMove)
    document.addEventListener('mouseup', handleMouseUp)
  }, [leftWidth])

  // 加载已保存的SQL到编辑器
  const handleLoadSql = (record) => {
    setSqlText(record.sql)
    if (record.conditions && record.conditions.length > 0) {
      setConditions(record.conditions)
    }
    setCurrentScriptId(record.id)
    // 如果脚本关联了数据库连接且当前未连接,提示用户
    if (record.connId && !connId) {
      message.info('该脚本关联了数据库连接,请先连接数据库后再执行')
    }
    message.success(`已加载: ${record.name}${record.conditions?.length ? `(含${record.conditions.length}个参数)` : ''}`)
  }

  // 自动同步当前参数到已加载的脚本(执行时触发)
  const syncConditionsToScript = async () => {
    if (!currentScriptId || conditions.length === 0) return
    try {
      // 序列化时把dayjs对象转为字符串,确保JSON正确保存
      const safeConditions = conditions.map(c => {
        const safe = { ...c }
        if (safe.value && dayjs.isDayjs(safe.value)) safe.value = safe.value.format('YYYY-MM-DD')
        if (safe.valueStart && dayjs.isDayjs(safe.valueStart)) safe.valueStart = safe.valueStart.format('YYYY-MM-DD')
        if (safe.valueEnd && dayjs.isDayjs(safe.valueEnd)) safe.valueEnd = safe.valueEnd.format('YYYY-MM-DD')
        return safe
      })
      await request.put(`/sql-manage/${currentScriptId}`, { conditions: safeConditions })
      // 同步成功后,更新本地conditions为格式化后的版本(确保后续渲染不会崩溃)
      setConditions(safeConditions)
    } catch {
      // 同步失败不影响主流程
    }
  }

  // 条件数量标记
  const conditionCount = conditions.length

  return (
    <div className="app-container">
      {/* 顶部栏 */}
      <div className="app-header">
        <div className="logo">SQL 报表工具</div>
        <div className="conn-info">
          {connInfo ? (
            <Space>
              <Tag color="green">{connInfo.name}</Tag>
              <span style={{ fontSize: 12, opacity: 0.8 }}>
                {connInfo.host}:{connInfo.port} / {connInfo.database}
              </span>
            </Space>
          ) : (
            <span style={{ fontSize: 12, opacity: 0.6 }}>未连接数据库</span>
          )}
          <Button
            size="small"
            type={connId ? 'default' : 'primary'}
            icon={<DatabaseOutlined />}
            onClick={() => setConnModalOpen(true)}
          >
            {connId ? '切换连接' : '连接数据库'}
          </Button>
        </div>
      </div>

      {/* 主体内容 */}
      <div className="app-body">
        {/* 左侧:SQL编辑器 */}
        {!leftCollapsed && (
          <div className="left-panel" style={{ width: `${leftWidth}%` }}>
            <div className="editor-toolbar">
              <Tooltip title="预检查SQL(语法+执行计划)">
                <Button
                  size="small"
                  icon={<SafetyCertificateOutlined />}
                  onClick={handleCheck}
                  disabled={!sqlText.trim()}
                >
                  预检查
                </Button>
              </Tooltip>
              <Tooltip title="直接执行SQL">
                <Button
                  size="small"
                  type="primary"
                  danger
                  icon={<PlayCircleOutlined />}
                  onClick={handleDirectExecute}
                  loading={execLoading}
                  disabled={!sqlText.trim()}
                >
                  执行
                </Button>
              </Tooltip>
              {/*<Tooltip title="格式化SQL代码">
                <Button
                  size="small"
                  icon={<FormatPainterOutlined />}
                  onClick={handleFormatSql}
                  disabled={!sqlText.trim()}
                >
                  格式化
                </Button>
              </Tooltip>*/}
              <Tooltip title="解析SQL中的 {{变量名}} 条件">
                <Button
                  size="small"
                  icon={<SearchOutlined />}
                  onClick={handleParseConditions}
                  disabled={!sqlText.trim()}
                >
                  解析条件
                </Button>
              </Tooltip>
              <Tooltip title="SQL脚本管理(含参数/邮件/定时配置)">
                <Button
                  size="small"
                  icon={<FolderOutlined />}
                  onClick={() => setSqlManagerOpen(true)}
                >
                  脚本管理
                </Button>
              </Tooltip>
              <Tooltip title="邮件发送配置">
                <Button
                  size="small"
                  icon={<MailOutlined />}
                  onClick={() => setSmtpConfigOpen(true)}
                >
                  邮件配置
                </Button>
              </Tooltip>
              <Tooltip title="配置查询条件">
                <Button
                  size="small"
                  icon={<SettingOutlined />}
                  onClick={() => setCondModalOpen(true)}
                >
                  条件{conditionCount > 0 ? `(${conditionCount})` : ''}
                </Button>
              </Tooltip>
            </div>

            <SqlEditor value={sqlText} onChange={setSqlText} />
          </div>
        )}

        {/* 拖动分隔条 */}
        <div
          className="resize-handle"
          onMouseDown={handleMouseDown}
        >
          <div
            className="collapse-btn"
            onClick={() => setLeftCollapsed(!leftCollapsed)}
            title={leftCollapsed ? '展开SQL面板' : '收起SQL面板'}
          >
            {leftCollapsed ? <RightOutlined /> : <LeftOutlined />}
          </div>
        </div>

        {/* 右侧:查询结果 */}
        <div className="right-panel" style={{
          width: leftCollapsed ? 'calc(100% - 12px)' : `${100 - leftWidth}%`,
          flexShrink: 0,
        }}>
          <ResultTable
            queryId={queryId}
            totalCount={resultTotal}
            columns={resultColumns}
            duration={resultDuration}
          />
        </div>
      </div>

      {/* 数据库连接弹窗 */}
      <ConnectionModal
        open={connModalOpen}
        onClose={() => setConnModalOpen(false)}
        onConnect={handleConnect}
        activeConnId={connId}
      />

      {/* 条件配置弹窗 */}
      <ConditionModal
        open={condModalOpen}
        onClose={() => setCondModalOpen(false)}
        conditions={conditions}
        onConditionsChange={setConditions}
        sqlText={sqlText}
        onParse={handleParseConditions}
      />

      {/* 执行预检弹窗 */}
      <ExecutionCheckModal
        open={checkModalOpen}
        onClose={() => setCheckModalOpen(false)}
        onConfirm={handleConfirmExecute}
        checkResult={checkResult}
        sql={finalSql}
      />

      {/* 错误报告弹窗 */}
      <ErrorReportModal
        open={errorModalOpen}
        onClose={() => setErrorModalOpen(false)}
        errorInfo={errorInfo}
      />

      {/* SQL脚本管理弹窗 */}
      <SqlManagerModal
        open={sqlManagerOpen}
        onClose={() => setSqlManagerOpen(false)}
        onLoadSql={handleLoadSql}
        currentSql={sqlText}
        currentConditions={conditions}
        connId={connId}
        currentScriptId={currentScriptId}
        onScriptIdChange={setCurrentScriptId}
      />

      {/* SMTP配置弹窗 */}
      <SmtpConfigModal
        open={smtpConfigOpen}
        onClose={() => setSmtpConfigOpen(false)}
      />
    </div>
  )
}