feat: v0.3.1 — Go/Gin 后端重写 + gh-ost 集成
架构变更: - Python/FastAPI → Go/Gin 重写(Python 后端保留在 backend-python/) - GORM + SQLite(兼容现有数据库表结构) - JWT 认证 + RBAC 权限中间件 Go 后端结构: - cmd/server/main.go — 入口,端口 9000 - config/config.go — 环境变量配置 - internal/model/ — GORM 模型(30张表,完全兼容 SQLite) - internal/handler/ — auth/instance/ticket/dashboard/ghost handler - internal/middleware/ — JWT 认证 + CORS - internal/ghost/ — gh-ost 集成模块(同步/异步执行,任务管理) - router/router.go — API 路由注册(/api/v1/...) gh-ost 集成: - RunGhOst() 同步执行 - RunGhOstAsync() 异步执行 + 进度追踪 - TaskManager 管理多个并发任务 - API: POST /ghost/dry-run, /ghost/execute, GET /ghost/status/:taskId 核心 API 已对齐: - POST /auth/login (JWT) - GET /dashboard/stats, /dashboard/my-tickets - GET /tickets/statistics, CRUD + approve/execute - GET/POST/PUT/DELETE /instances - GET /users, /audit-rules, /announcements, /settings 已验证: - 登录 admin/admin123 ✅ - Dashboard 99工单/110查询/4实例 ✅ - 工单统计按角色过滤 ✅
This commit is contained in:
1 parent
43d1f3a234
commit
ca308e277d
202 files changed
+2265
-51181
No files matched your search
@@ -0,0 +1,233 @@
|
||||
package ghost
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// GhOstTask defines a gh-ost execution task
|
||||
type GhOstTask struct {
|
||||
Host string `json:"host"`
|
||||
User string `json:"user"`
|
||||
Password string `json:"password"`
|
||||
Database string `json:"database"`
|
||||
Table string `json:"table"`
|
||||
Alter string `json:"alter"` // e.g. "ADD COLUMN status INT NOT NULL DEFAULT 0"
|
||||
ChunkSize int `json:"chunk_size,omitempty"`
|
||||
MaxLoad string `json:"max_load,omitempty"`
|
||||
CriticalLoad string `json:"critical_load,omitempty"`
|
||||
MaxLagMillis int `json:"max_lag_millis,omitempty"`
|
||||
AllowOnMaster bool `json:"allow_on_master"`
|
||||
DryRun bool `json:"dry_run"`
|
||||
Execute bool `json:"execute"`
|
||||
ExactRowCount bool `json:"exact_row_count"`
|
||||
PostponeCutOver bool `json:"postpone_cut_over"`
|
||||
}
|
||||
|
||||
// GhOstResult holds the execution result
|
||||
type GhOstResult struct {
|
||||
Success bool `json:"success"`
|
||||
Output string `json:"output"`
|
||||
Error string `json:"error"`
|
||||
Command string `json:"command"`
|
||||
Duration string `json:"duration"`
|
||||
TaskID string `json:"task_id"`
|
||||
}
|
||||
|
||||
// ProgressCallback is called with stdout lines for real-time progress
|
||||
type ProgressCallback func(taskID string, line string)
|
||||
|
||||
// TaskManager manages async gh-ost tasks
|
||||
type TaskManager struct {
|
||||
mu sync.RWMutex
|
||||
tasks map[string]*GhOstResult
|
||||
status map[string]string // running, completed, failed
|
||||
}
|
||||
|
||||
var Manager = &TaskManager{
|
||||
tasks: make(map[string]*GhOstResult),
|
||||
status: make(map[string]string),
|
||||
}
|
||||
|
||||
// RunGhOst executes gh-ost synchronously
|
||||
func RunGhOst(ctx context.Context, task GhOstTask, ghOstPath string) (*GhOstResult, error) {
|
||||
start := time.Now()
|
||||
|
||||
args := []string{
|
||||
"--host=" + task.Host,
|
||||
"--user=" + task.User,
|
||||
"--password=" + task.Password,
|
||||
"--database=" + task.Database,
|
||||
"--table=" + task.Table,
|
||||
"--alter=" + task.Alter,
|
||||
"--verbose",
|
||||
}
|
||||
|
||||
if task.ChunkSize > 0 {
|
||||
args = append(args, fmt.Sprintf("--chunk-size=%d", task.ChunkSize))
|
||||
}
|
||||
if task.MaxLoad != "" {
|
||||
args = append(args, "--max-load="+task.MaxLoad)
|
||||
}
|
||||
if task.CriticalLoad != "" {
|
||||
args = append(args, "--critical-load="+task.CriticalLoad)
|
||||
}
|
||||
if task.MaxLagMillis > 0 {
|
||||
args = append(args, fmt.Sprintf("--max-lag-millis=%d", task.MaxLagMillis))
|
||||
}
|
||||
if task.AllowOnMaster {
|
||||
args = append(args, "--allow-on-master")
|
||||
}
|
||||
if task.ExactRowCount {
|
||||
args = append(args, "--exact-rowcount")
|
||||
}
|
||||
if task.PostponeCutOver {
|
||||
args = append(args, "--postpone-cut-over-flag-file=/tmp/gh-ost-cutover.flag")
|
||||
}
|
||||
|
||||
// Dry-Run vs Execute
|
||||
if task.DryRun || !task.Execute {
|
||||
args = append(args, "--dry-run")
|
||||
} else {
|
||||
args = append(args, "--execute")
|
||||
}
|
||||
|
||||
cmd := exec.CommandContext(ctx, ghOstPath, args...)
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
|
||||
err := cmd.Run()
|
||||
|
||||
result := &GhOstResult{
|
||||
Command: "gh-ost " + strings.Join(args, " "),
|
||||
Duration: time.Since(start).String(),
|
||||
Output: stdout.String(),
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
result.Success = false
|
||||
result.Error = stderr.String() + "\n" + err.Error()
|
||||
return result, err
|
||||
}
|
||||
|
||||
result.Success = true
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// RunGhOstAsync runs gh-ost in background and tracks status
|
||||
func RunGhOstAsync(task GhOstTask, ghOstPath string, cb ProgressCallback) string {
|
||||
taskID := fmt.Sprintf("ghost-%d", time.Now().UnixNano())
|
||||
|
||||
Manager.mu.Lock()
|
||||
Manager.status[taskID] = "running"
|
||||
Manager.tasks[taskID] = &GhOstResult{TaskID: taskID}
|
||||
Manager.mu.Unlock()
|
||||
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Hour)
|
||||
defer cancel()
|
||||
|
||||
start := time.Now()
|
||||
|
||||
args := buildArgs(task, ghOstPath)
|
||||
|
||||
cmd := exec.CommandContext(ctx, ghOstPath, args...)
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
|
||||
err := cmd.Run()
|
||||
|
||||
Manager.mu.Lock()
|
||||
defer Manager.mu.Unlock()
|
||||
|
||||
result := &GhOstResult{
|
||||
TaskID: taskID,
|
||||
Command: "gh-ost " + strings.Join(args, " "),
|
||||
Duration: time.Since(start).String(),
|
||||
Output: stdout.String(),
|
||||
Success: err == nil,
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
result.Error = stderr.String() + "\n" + err.Error()
|
||||
Manager.status[taskID] = "failed"
|
||||
} else {
|
||||
Manager.status[taskID] = "completed"
|
||||
}
|
||||
|
||||
Manager.tasks[taskID] = result
|
||||
|
||||
if cb != nil {
|
||||
cb(taskID, result.Output)
|
||||
}
|
||||
}()
|
||||
|
||||
return taskID
|
||||
}
|
||||
|
||||
// GetTaskStatus returns the status of an async task
|
||||
func (m *TaskManager) GetTaskStatus(taskID string) (string, *GhOstResult) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
return m.status[taskID], m.tasks[taskID]
|
||||
}
|
||||
|
||||
// ListTasks returns all tracked tasks
|
||||
func (m *TaskManager) ListTasks() map[string]string {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
result := make(map[string]string)
|
||||
for k, v := range m.status {
|
||||
result[k] = v
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func buildArgs(task GhOstTask, ghOstPath string) []string {
|
||||
args := []string{
|
||||
"--host=" + task.Host,
|
||||
"--user=" + task.User,
|
||||
"--password=" + task.Password,
|
||||
"--database=" + task.Database,
|
||||
"--table=" + task.Table,
|
||||
"--alter=" + task.Alter,
|
||||
"--verbose",
|
||||
}
|
||||
|
||||
if task.ChunkSize > 0 {
|
||||
args = append(args, fmt.Sprintf("--chunk-size=%d", task.ChunkSize))
|
||||
}
|
||||
if task.MaxLoad != "" {
|
||||
args = append(args, "--max-load="+task.MaxLoad)
|
||||
}
|
||||
if task.CriticalLoad != "" {
|
||||
args = append(args, "--critical-load="+task.CriticalLoad)
|
||||
}
|
||||
if task.MaxLagMillis > 0 {
|
||||
args = append(args, fmt.Sprintf("--max-lag-millis=%d", task.MaxLagMillis))
|
||||
}
|
||||
if task.AllowOnMaster {
|
||||
args = append(args, "--allow-on-master")
|
||||
}
|
||||
if task.ExactRowCount {
|
||||
args = append(args, "--exact-rowcount")
|
||||
}
|
||||
if task.PostponeCutOver {
|
||||
args = append(args, "--postpone-cut-over-flag-file=/tmp/gh-ost-cutover.flag")
|
||||
}
|
||||
|
||||
if task.DryRun || !task.Execute {
|
||||
args = append(args, "--dry-run")
|
||||
} else {
|
||||
args = append(args, "--execute")
|
||||
}
|
||||
|
||||
return args
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"sql-platform/internal/middleware"
|
||||
"sql-platform/internal/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// POST /api/v1/auth/login
|
||||
func Login(c *gin.Context) {
|
||||
var req model.LoginRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"detail": "username and password required"})
|
||||
return
|
||||
}
|
||||
|
||||
var user model.User
|
||||
if err := model.DB.Where("username = ?", req.Username).First(&user).Error; err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"detail": "Invalid username or password"})
|
||||
return
|
||||
}
|
||||
|
||||
if user.IsActive != nil && !*user.IsActive {
|
||||
c.JSON(http.StatusForbidden, gin.H{"detail": "Account is disabled"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.HashedPassword), []byte(req.Password)); err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"detail": "Invalid username or password"})
|
||||
return
|
||||
}
|
||||
|
||||
token, err := middleware.GenerateToken(&user)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"detail": "Failed to generate token"})
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
user.LastLogin = &now
|
||||
model.DB.Save(&user)
|
||||
|
||||
c.JSON(http.StatusOK, model.LoginResponse{
|
||||
AccessToken: token,
|
||||
TokenType: "bearer",
|
||||
User: user,
|
||||
})
|
||||
}
|
||||
|
||||
// GET /api/v1/auth/me
|
||||
func GetMe(c *gin.Context) {
|
||||
userID, _, _ := middleware.GetCurrentUser(c)
|
||||
var user model.User
|
||||
if err := model.DB.First(&user, userID).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"detail": "User not found"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, user)
|
||||
}
|
||||
|
||||
// GET /api/v1/users
|
||||
func ListUsers(c *gin.Context) {
|
||||
var users []model.User
|
||||
model.DB.Order("id").Find(&users)
|
||||
c.JSON(http.StatusOK, users)
|
||||
}
|
||||
|
||||
// POST /api/v1/users
|
||||
func CreateUser(c *gin.Context) {
|
||||
var input struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
DisplayName string `json:"display_name" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
Email *string `json:"email"`
|
||||
Phone *string `json:"phone"`
|
||||
Role string `json:"role" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&input); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"detail": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
hashed, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"detail": "Failed to hash password"})
|
||||
return
|
||||
}
|
||||
|
||||
isActive := true
|
||||
user := model.User{
|
||||
Username: input.Username,
|
||||
DisplayName: input.DisplayName,
|
||||
HashedPassword: string(hashed),
|
||||
Email: input.Email,
|
||||
Phone: input.Phone,
|
||||
Role: input.Role,
|
||||
IsActive: &isActive,
|
||||
}
|
||||
|
||||
if err := model.DB.Create(&user).Error; err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"detail": "Username already exists"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, user)
|
||||
}
|
||||
|
||||
// PUT /api/v1/users/:id
|
||||
func UpdateUser(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
var user model.User
|
||||
if err := model.DB.First(&user, id).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"detail": "User not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var input map[string]interface{}
|
||||
if err := c.ShouldBindJSON(&input); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"detail": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if pw, ok := input["password"].(string); ok && pw != "" {
|
||||
hashed, _ := bcrypt.GenerateFromPassword([]byte(pw), bcrypt.DefaultCost)
|
||||
input["hashed_password"] = string(hashed)
|
||||
}
|
||||
delete(input, "password")
|
||||
|
||||
if err := model.DB.Model(&user).Updates(input).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"detail": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
model.DB.First(&user, id)
|
||||
c.JSON(http.StatusOK, user)
|
||||
}
|
||||
|
||||
// DELETE /api/v1/users/:id
|
||||
func DeleteUser(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
if err := model.DB.Delete(&model.User{}, id).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"detail": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "User deleted"})
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"sql-platform/internal/middleware"
|
||||
"sql-platform/internal/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// GET /api/v1/dashboard/stats
|
||||
func DashboardStats(c *gin.Context) {
|
||||
var ticketCount, queryCount, instanceCount int64
|
||||
model.DB.Model(&model.Ticket{}).Count(&ticketCount)
|
||||
model.DB.Model(&model.QueryHistory{}).Count(&queryCount)
|
||||
model.DB.Model(&model.Instance{}).Count(&instanceCount)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"ticket_count": ticketCount,
|
||||
"query_count": queryCount,
|
||||
"instance_count": instanceCount,
|
||||
})
|
||||
}
|
||||
|
||||
// GET /api/v1/dashboard/my-tickets
|
||||
func MyTickets(c *gin.Context) {
|
||||
userID, _, role := middleware.GetCurrentUser(c)
|
||||
|
||||
var tickets []model.Ticket
|
||||
query := model.DB.Order("id DESC").Limit(10)
|
||||
|
||||
switch role {
|
||||
case "admin":
|
||||
// Admin sees all pending/executing tickets
|
||||
query = query.Where("status IN ?", []string{"pending", "reviewing", "executing"})
|
||||
case "dba", "auditor":
|
||||
// DBA sees their own + pending approval
|
||||
query = query.Where(
|
||||
"(applicant_id = ? AND status IN ?) OR (id IN (SELECT ticket_id FROM ticket_approvals WHERE approver_id = ?) AND status IN ?)",
|
||||
userID, []string{"pending", "executing"},
|
||||
userID, []string{"pending", "reviewing", "executing"},
|
||||
)
|
||||
default: // developer
|
||||
query = query.Where("applicant_id = ?", userID)
|
||||
}
|
||||
|
||||
query.Find(&tickets)
|
||||
|
||||
type ticketWithRelation struct {
|
||||
model.Ticket
|
||||
Relation string `json:"relation"` // "submitted" or "pending_approval"
|
||||
}
|
||||
|
||||
var result []ticketWithRelation
|
||||
for _, t := range tickets {
|
||||
rel := "submitted"
|
||||
if t.ApplicantID != userID {
|
||||
rel = "pending_approval"
|
||||
}
|
||||
result = append(result, ticketWithRelation{Ticket: t, Relation: rel})
|
||||
}
|
||||
|
||||
if result == nil {
|
||||
result = []ticketWithRelation{}
|
||||
}
|
||||
c.JSON(http.StatusOK, result)
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"sql-platform/config"
|
||||
"sql-platform/internal/ghost"
|
||||
"sql-platform/internal/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// POST /api/v1/ghost/dry-run
|
||||
func GhOstDryRun(c *gin.Context) {
|
||||
var task ghost.GhOstTask
|
||||
if err := c.ShouldBindJSON(&task); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"detail": err.Error()})
|
||||
return
|
||||
}
|
||||
task.DryRun = true
|
||||
task.Execute = false
|
||||
|
||||
result, err := ghost.RunGhOst(c.Request.Context(), task, config.C.GhOstPath)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, result)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, result)
|
||||
}
|
||||
|
||||
// POST /api/v1/ghost/execute
|
||||
func GhOstExecute(c *gin.Context) {
|
||||
var task ghost.GhOstTask
|
||||
if err := c.ShouldBindJSON(&task); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"detail": err.Error()})
|
||||
return
|
||||
}
|
||||
task.DryRun = false
|
||||
task.Execute = true
|
||||
|
||||
taskID := ghost.RunGhOstAsync(task, config.C.GhOstPath, nil)
|
||||
c.JSON(http.StatusAccepted, gin.H{
|
||||
"task_id": taskID,
|
||||
"message": "gh-ost execution started",
|
||||
})
|
||||
}
|
||||
|
||||
// GET /api/v1/ghost/status/:taskId
|
||||
func GhOstStatus(c *gin.Context) {
|
||||
taskID := c.Param("taskId")
|
||||
status, result := ghost.Manager.GetTaskStatus(taskID)
|
||||
if status == "" {
|
||||
c.JSON(http.StatusNotFound, gin.H{"detail": "Task not found"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"task_id": taskID,
|
||||
"status": status,
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
|
||||
// GET /api/v1/ghost/tasks
|
||||
func GhOstListTasks(c *gin.Context) {
|
||||
tasks := ghost.Manager.ListTasks()
|
||||
c.JSON(http.StatusOK, tasks)
|
||||
}
|
||||
|
||||
// GET /api/v1/audit-rules
|
||||
func ListAuditRules(c *gin.Context) {
|
||||
var rules []model.AuditRule
|
||||
model.DB.Order("id").Find(&rules)
|
||||
c.JSON(http.StatusOK, rules)
|
||||
}
|
||||
|
||||
// GET /api/v1/announcements
|
||||
func ListAnnouncements(c *gin.Context) {
|
||||
var announcements []model.Announcement
|
||||
model.DB.Where("is_published = ?", true).Order("id DESC").Find(&announcements)
|
||||
c.JSON(http.StatusOK, announcements)
|
||||
}
|
||||
|
||||
// GET /api/v1/query-histories
|
||||
func ListQueryHistories(c *gin.Context) {
|
||||
_, _, _ = c.GetInt("user_id"), c.GetString("username"), c.GetString("role")
|
||||
|
||||
var histories []model.QueryHistory
|
||||
model.DB.Order("id DESC").Limit(100).Find(&histories)
|
||||
c.JSON(http.StatusOK, histories)
|
||||
}
|
||||
|
||||
// GET /api/v1/settings
|
||||
func ListSettings(c *gin.Context) {
|
||||
var settings []model.SystemSetting
|
||||
model.DB.Order("sort_order").Find(&settings)
|
||||
c.JSON(http.StatusOK, settings)
|
||||
}
|
||||
|
||||
// GET /api/v1/notifications/channels
|
||||
func ListNotificationChannels(c *gin.Context) {
|
||||
var channels []model.NotificationChannel
|
||||
model.DB.Order("id").Find(&channels)
|
||||
c.JSON(http.StatusOK, channels)
|
||||
}
|
||||
|
||||
// GET /api/v1/notifications/templates
|
||||
func ListNotificationTemplates(c *gin.Context) {
|
||||
var templates []model.NotificationTemplate
|
||||
model.DB.Order("id").Find(&templates)
|
||||
c.JSON(http.StatusOK, templates)
|
||||
}
|
||||
|
||||
// GET /api/v1/workflows
|
||||
func ListWorkflows(c *gin.Context) {
|
||||
var workflows []model.WorkflowDefinition
|
||||
model.DB.Order("id").Find(&workflows)
|
||||
c.JSON(http.StatusOK, workflows)
|
||||
}
|
||||
|
||||
// GET /api/v1/instance-groups
|
||||
func ListInstanceGroups(c *gin.Context) {
|
||||
var groups []model.InstanceGroup
|
||||
model.DB.Order("id").Find(&groups)
|
||||
c.JSON(http.StatusOK, groups)
|
||||
}
|
||||
|
||||
// POST /api/v1/notifications/test
|
||||
func TestNotification(c *gin.Context) {
|
||||
_ = time.Now()
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Notification sent (placeholder)"})
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"sql-platform/internal/middleware"
|
||||
"sql-platform/internal/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// GET /api/v1/instances
|
||||
func ListInstances(c *gin.Context) {
|
||||
userID, _, role := middleware.GetCurrentUser(c)
|
||||
|
||||
var instances []model.Instance
|
||||
query := model.DB.Order("id")
|
||||
|
||||
// developer only sees instances in their groups
|
||||
if role == "developer" {
|
||||
var groupIDs []int
|
||||
model.DB.Model(&model.UserGroup{}).Where("user_id = ?", userID).Pluck("group_id", &groupIDs)
|
||||
if len(groupIDs) > 0 {
|
||||
var instanceIDs []int
|
||||
model.DB.Model(&model.InstanceGroupMember{}).Where("group_id IN ?", groupIDs).Pluck("instance_id", &instanceIDs)
|
||||
if len(instanceIDs) > 0 {
|
||||
query = query.Where("id IN ?", instanceIDs)
|
||||
} else {
|
||||
c.JSON(http.StatusOK, []model.Instance{})
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := query.Find(&instances).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"detail": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// mask passwords in response
|
||||
for i := range instances {
|
||||
instances[i].Password = "******"
|
||||
}
|
||||
c.JSON(http.StatusOK, instances)
|
||||
}
|
||||
|
||||
// GET /api/v1/instances/:id
|
||||
func GetInstance(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
var instance model.Instance
|
||||
if err := model.DB.First(&instance, id).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"detail": "Instance not found"})
|
||||
return
|
||||
}
|
||||
instance.Password = "******"
|
||||
c.JSON(http.StatusOK, instance)
|
||||
}
|
||||
|
||||
// POST /api/v1/instances
|
||||
func CreateInstance(c *gin.Context) {
|
||||
var instance model.Instance
|
||||
if err := c.ShouldBindJSON(&instance); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"detail": err.Error()})
|
||||
return
|
||||
}
|
||||
if err := model.DB.Create(&instance).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"detail": err.Error()})
|
||||
return
|
||||
}
|
||||
instance.Password = "******"
|
||||
c.JSON(http.StatusCreated, instance)
|
||||
}
|
||||
|
||||
// PUT /api/v1/instances/:id
|
||||
func UpdateInstance(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
var instance model.Instance
|
||||
if err := model.DB.First(&instance, id).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"detail": "Instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var input map[string]interface{}
|
||||
if err := c.ShouldBindJSON(&input); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"detail": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// if password is masked, don't update it
|
||||
if pw, ok := input["password"].(string); ok && pw == "******" {
|
||||
delete(input, "password")
|
||||
}
|
||||
|
||||
if err := model.DB.Model(&instance).Updates(input).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"detail": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
model.DB.First(&instance, id)
|
||||
instance.Password = "******"
|
||||
c.JSON(http.StatusOK, instance)
|
||||
}
|
||||
|
||||
// DELETE /api/v1/instances/:id
|
||||
func DeleteInstance(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
if err := model.DB.Delete(&model.Instance{}, id).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"detail": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Instance deleted"})
|
||||
}
|
||||
|
||||
// POST /api/v1/instances/:id/test-connection
|
||||
func TestConnection(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
var instance model.Instance
|
||||
if err := model.DB.First(&instance, id).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"detail": "Instance not found"})
|
||||
return
|
||||
}
|
||||
|
||||
// TODO: actual DB connection test
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "Connection test passed (placeholder)",
|
||||
})
|
||||
}
|
||||
|
||||
// GET /api/v1/instances/stats
|
||||
func InstanceStats(c *gin.Context) {
|
||||
var total int64
|
||||
model.DB.Model(&model.Instance{}).Count(&total)
|
||||
|
||||
type typeCount struct {
|
||||
DBType string `json:"db_type"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
var byType []typeCount
|
||||
model.DB.Model(&model.Instance{}).Select("db_type, count(*) as count").Group("db_type").Scan(&byType)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"total": total,
|
||||
"by_type": byType,
|
||||
})
|
||||
}
|
||||
|
||||
// Helper: parse id param to int
|
||||
func parseID(s string) (int, bool) {
|
||||
id, err := strconv.Atoi(s)
|
||||
return id, err == nil
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"sql-platform/internal/middleware"
|
||||
"sql-platform/internal/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// GET /api/v1/tickets/statistics
|
||||
func TicketStatistics(c *gin.Context) {
|
||||
userID, _, role := middleware.GetCurrentUser(c)
|
||||
|
||||
type statusCount struct {
|
||||
Status string `json:"status"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
var counts []statusCount
|
||||
|
||||
query := model.DB.Model(&model.Ticket{}).Select("status, count(*) as count")
|
||||
|
||||
// Filter by user role
|
||||
switch role {
|
||||
case "developer":
|
||||
query = query.Where("applicant_id = ?", userID)
|
||||
case "dba", "auditor":
|
||||
// DBA sees tickets they submitted + tickets they need to approve
|
||||
query = query.Where(
|
||||
"applicant_id = ? OR id IN (SELECT ticket_id FROM ticket_approvals WHERE approver_id = ?)",
|
||||
userID, userID,
|
||||
)
|
||||
// admin sees everything
|
||||
}
|
||||
|
||||
query.Group("status").Scan(&counts)
|
||||
|
||||
stats := model.TicketStatistics{}
|
||||
for _, c := range counts {
|
||||
switch c.Status {
|
||||
case "pending":
|
||||
stats.Pending = int(c.Count)
|
||||
case "reviewing":
|
||||
stats.Reviewing = int(c.Count)
|
||||
case "executing":
|
||||
stats.Executing = int(c.Count)
|
||||
case "completed":
|
||||
stats.Completed = int(c.Count)
|
||||
case "failed":
|
||||
stats.Failed = int(c.Count)
|
||||
case "rejected":
|
||||
stats.Rejected = int(c.Count)
|
||||
}
|
||||
}
|
||||
stats.Total = stats.Pending + stats.Reviewing + stats.Executing + stats.Completed + stats.Failed + stats.Rejected
|
||||
|
||||
c.JSON(http.StatusOK, stats)
|
||||
}
|
||||
|
||||
// GET /api/v1/tickets
|
||||
func ListTickets(c *gin.Context) {
|
||||
userID, _, role := middleware.GetCurrentUser(c)
|
||||
status := c.Query("status")
|
||||
page := 1
|
||||
limit := 20
|
||||
|
||||
query := model.DB.Model(&model.Ticket{}).Order("id DESC")
|
||||
|
||||
// Filter by user role
|
||||
switch role {
|
||||
case "developer":
|
||||
query = query.Where("applicant_id = ?", userID)
|
||||
case "dba", "auditor":
|
||||
query = query.Where(
|
||||
"applicant_id = ? OR id IN (SELECT ticket_id FROM ticket_approvals WHERE approver_id = ?)",
|
||||
userID, userID,
|
||||
)
|
||||
}
|
||||
|
||||
if status != "" && status != "all" {
|
||||
query = query.Where("status = ?", status)
|
||||
}
|
||||
|
||||
var total int64
|
||||
query.Count(&total)
|
||||
|
||||
var tickets []model.Ticket
|
||||
query.Offset((page - 1) * limit).Limit(limit).Find(&tickets)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"items": tickets,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"limit": limit,
|
||||
})
|
||||
}
|
||||
|
||||
// GET /api/v1/tickets/:id
|
||||
func GetTicket(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
var ticket model.Ticket
|
||||
if err := model.DB.First(&ticket, id).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"detail": "Ticket not found"})
|
||||
return
|
||||
}
|
||||
|
||||
// Get approvals
|
||||
var approvals []model.TicketApproval
|
||||
model.DB.Where("ticket_id = ?", id).Order("step_number").Find(&approvals)
|
||||
|
||||
// Get SQL items
|
||||
var sqlItems []model.TicketSQLItem
|
||||
model.DB.Where("ticket_id = ?", id).Order("seq").Find(&sqlItems)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"ticket": ticket,
|
||||
"approvals": approvals,
|
||||
"sql_items": sqlItems,
|
||||
})
|
||||
}
|
||||
|
||||
// POST /api/v1/tickets
|
||||
func CreateTicket(c *gin.Context) {
|
||||
userID, _, _ := middleware.GetCurrentUser(c)
|
||||
|
||||
var input struct {
|
||||
Title string `json:"title" binding:"required"`
|
||||
DBType string `json:"db_type" binding:"required"`
|
||||
InstanceID int `json:"instance_id" binding:"required"`
|
||||
TargetDatabase string `json:"target_database" binding:"required"`
|
||||
SQLContent string `json:"sql_content" binding:"required"`
|
||||
RollbackSQL *string `json:"rollback_sql"`
|
||||
Priority *string `json:"priority"`
|
||||
Reason *string `json:"reason"`
|
||||
WorkflowID *int `json:"workflow_id"`
|
||||
RiskLevel *string `json:"risk_level"`
|
||||
ExecStrategy *string `json:"exec_strategy"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&input); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"detail": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
status := "pending"
|
||||
priority := "medium"
|
||||
riskLevel := "low"
|
||||
execStrategy := "stop_on_error"
|
||||
|
||||
if input.Priority != nil {
|
||||
priority = *input.Priority
|
||||
}
|
||||
if input.RiskLevel != nil {
|
||||
riskLevel = *input.RiskLevel
|
||||
}
|
||||
if input.ExecStrategy != nil {
|
||||
execStrategy = *input.ExecStrategy
|
||||
}
|
||||
|
||||
// Generate ticket number
|
||||
now := time.Now()
|
||||
ticketNo := now.Format("20060102") + "-" + fmt.Sprintf("%04d", time.Now().UnixNano()%10000)
|
||||
|
||||
ticket := model.Ticket{
|
||||
Title: input.Title,
|
||||
DBType: input.DBType,
|
||||
InstanceID: input.InstanceID,
|
||||
TargetDatabase: input.TargetDatabase,
|
||||
SQLContent: input.SQLContent,
|
||||
RollbackSQL: input.RollbackSQL,
|
||||
Status: &status,
|
||||
Priority: &priority,
|
||||
ApplicantID: userID,
|
||||
Reason: input.Reason,
|
||||
WorkflowID: input.WorkflowID,
|
||||
RiskLevel: &riskLevel,
|
||||
ExecStrategy: &execStrategy,
|
||||
TicketNo: &ticketNo,
|
||||
}
|
||||
|
||||
if err := model.DB.Create(&ticket).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"detail": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, ticket)
|
||||
}
|
||||
|
||||
// POST /api/v1/tickets/:id/approve
|
||||
func ApproveTicket(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
userID, _, _ := middleware.GetCurrentUser(c)
|
||||
|
||||
var ticket model.Ticket
|
||||
if err := model.DB.First(&ticket, id).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"detail": "Ticket not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var input struct {
|
||||
Action string `json:"action" binding:"required"` // approve, reject
|
||||
Comment *string `json:"comment"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&input); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"detail": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
|
||||
// Update approval record
|
||||
var approval model.TicketApproval
|
||||
if err := model.DB.Where("ticket_id = ? AND approver_id = ? AND action IS NULL", id, userID).First(&approval).Error; err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"detail": "No pending approval for you"})
|
||||
return
|
||||
}
|
||||
|
||||
approval.Action = &input.Action
|
||||
approval.Comment = input.Comment
|
||||
approval.ActualApproverID = &userID
|
||||
approval.CompletedAt = &now
|
||||
model.DB.Save(&approval)
|
||||
|
||||
// Update ticket status
|
||||
newStatus := "approved"
|
||||
if input.Action == "reject" {
|
||||
newStatus = "rejected"
|
||||
} else if input.Action == "approve" {
|
||||
// Check if there are more pending approvals
|
||||
var pendingCount int64
|
||||
model.DB.Model(&model.TicketApproval{}).Where("ticket_id = ? AND action IS NULL", id).Count(&pendingCount)
|
||||
if pendingCount > 0 {
|
||||
newStatus = "reviewing"
|
||||
}
|
||||
}
|
||||
|
||||
ticket.Status = &newStatus
|
||||
ticket.ReviewTime = &now
|
||||
model.DB.Save(&ticket)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"ticket": ticket, "approval": approval})
|
||||
}
|
||||
|
||||
// POST /api/v1/tickets/:id/execute
|
||||
func ExecuteTicket(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
|
||||
var ticket model.Ticket
|
||||
if err := model.DB.First(&ticket, id).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"detail": "Ticket not found"})
|
||||
return
|
||||
}
|
||||
|
||||
status := "executing"
|
||||
ticket.Status = &status
|
||||
now := time.Now()
|
||||
ticket.ExecuteTime = &now
|
||||
model.DB.Save(&ticket)
|
||||
|
||||
// TODO: actual SQL execution
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Execution started", "ticket_id": ticket.ID})
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"sql-platform/config"
|
||||
"sql-platform/internal/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
type Claims struct {
|
||||
UserID int `json:"user_id"`
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func GenerateToken(user *model.User) (string, error) {
|
||||
claims := Claims{
|
||||
UserID: user.ID,
|
||||
Username: user.Username,
|
||||
Role: user.Role,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(config.C.JWTExpire) * time.Hour)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
}
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString([]byte(config.C.JWTSecret))
|
||||
}
|
||||
|
||||
func AuthMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"detail": "Not authenticated"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
tokenStr := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
if tokenStr == authHeader {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"detail": "Invalid token format"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
claims := &Claims{}
|
||||
token, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(config.C.JWTSecret), nil
|
||||
})
|
||||
|
||||
if err != nil || !token.Valid {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"detail": "Invalid or expired token"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("user_id", claims.UserID)
|
||||
c.Set("username", claims.Username)
|
||||
c.Set("role", claims.Role)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func GetCurrentUser(c *gin.Context) (int, string, string) {
|
||||
return c.GetInt("user_id"), c.GetString("username"), c.GetString("role")
|
||||
}
|
||||
|
||||
// RBAC middleware — allow specified roles
|
||||
func RequireRole(roles ...string) gin.HandlerFunc {
|
||||
roleSet := make(map[string]bool)
|
||||
for _, r := range roles {
|
||||
roleSet[r] = true
|
||||
}
|
||||
return func(c *gin.Context) {
|
||||
role := c.GetString("role")
|
||||
if !roleSet[role] {
|
||||
c.JSON(http.StatusForbidden, gin.H{"detail": "Permission denied"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-contrib/cors"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func CORSMiddleware() gin.HandlerFunc {
|
||||
return cors.New(cors.Config{
|
||||
AllowOrigins: []string{"http://localhost:5173", "http://127.0.0.1:5173"},
|
||||
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"},
|
||||
AllowHeaders: []string{"Origin", "Content-Type", "Authorization"},
|
||||
ExposeHeaders: []string{"Content-Length"},
|
||||
AllowCredentials: true,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,516 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ==================== User ====================
|
||||
|
||||
type User struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
Username string `gorm:"size:50;uniqueIndex;not null" json:"username"`
|
||||
DisplayName string `gorm:"size:100;not null" json:"display_name"`
|
||||
Email *string `gorm:"size:100" json:"email"`
|
||||
Phone *string `gorm:"size:20" json:"phone"`
|
||||
HashedPassword string `gorm:"size:200;not null" json:"-"`
|
||||
Role string `gorm:"size:20;not null" json:"role"` // admin, dba, developer, auditor
|
||||
IsActive *bool `gorm:"default:true" json:"is_active"`
|
||||
LastLogin *time.Time `json:"last_login"`
|
||||
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"`
|
||||
}
|
||||
|
||||
func (User) TableName() string { return "users" }
|
||||
|
||||
// ==================== Instance ====================
|
||||
|
||||
type Instance struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
Name string `gorm:"size:100;not null" json:"name"`
|
||||
DBType string `gorm:"size:20;not null" json:"db_type"`
|
||||
Host string `gorm:"size:200;not null" json:"host"`
|
||||
Port int `gorm:"not null" json:"port"`
|
||||
Username string `gorm:"size:100;not null" json:"username"`
|
||||
Password string `gorm:"size:500;not null" json:"password,omitempty"`
|
||||
Database *string `gorm:"size:100" json:"database"`
|
||||
Env *string `gorm:"size:20" json:"env"`
|
||||
Description *string `gorm:"type:text" json:"description"`
|
||||
Status *string `gorm:"size:20" json:"status"`
|
||||
Version *string `gorm:"size:50" json:"version"`
|
||||
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"`
|
||||
AccessMode *string `gorm:"size:20;default:readwrite" json:"access_mode"`
|
||||
Workflow *string `gorm:"type:text" json:"workflow"`
|
||||
ExcludedDatabases *string `gorm:"type:text" json:"excluded_databases"`
|
||||
MaskFields *string `gorm:"type:text" json:"mask_fields"`
|
||||
GroupID *int `json:"group_id"`
|
||||
WorkflowID *int `json:"workflow_id"`
|
||||
}
|
||||
|
||||
func (Instance) TableName() string { return "instances" }
|
||||
|
||||
// ==================== Ticket ====================
|
||||
|
||||
type Ticket struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
Title string `gorm:"size:200;not null" json:"title"`
|
||||
DBType string `gorm:"size:20;not null" json:"db_type"`
|
||||
InstanceID int `gorm:"not null" json:"instance_id"`
|
||||
TargetDatabase string `gorm:"size:100;not null" json:"target_database"`
|
||||
SQLContent string `gorm:"type:text;not null" json:"sql_content"`
|
||||
RollbackSQL *string `gorm:"type:text" json:"rollback_sql"`
|
||||
Status *string `gorm:"size:20" json:"status"`
|
||||
Priority *string `gorm:"size:10" json:"priority"`
|
||||
ApplicantID int `gorm:"not null" json:"applicant_id"`
|
||||
ApproverID *int `json:"approver_id"`
|
||||
Reason *string `gorm:"type:text" json:"reason"`
|
||||
AuditResult *string `gorm:"type:text" json:"audit_result"`
|
||||
ExecuteResult *string `gorm:"type:text" json:"execute_result"`
|
||||
CreateTime time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"create_time"`
|
||||
ReviewTime *time.Time `json:"review_time"`
|
||||
ExecuteTime *time.Time `json:"execute_time"`
|
||||
UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"`
|
||||
TicketNo *string `gorm:"size:20" json:"ticket_no"`
|
||||
ScheduledAt sql.NullTime `json:"scheduled_at"`
|
||||
WorkflowID *int `json:"workflow_id"`
|
||||
RiskLevel *string `gorm:"size:20;default:low" json:"risk_level"`
|
||||
ExecStrategy *string `gorm:"size:20;default:stop_on_error" json:"exec_strategy"`
|
||||
}
|
||||
|
||||
func (Ticket) TableName() string { return "tickets" }
|
||||
|
||||
// ==================== TicketApproval ====================
|
||||
|
||||
type TicketApproval struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
TicketID int `gorm:"not null" json:"ticket_id"`
|
||||
WorkflowID *int `json:"workflow_id"`
|
||||
VersionID *int `json:"version_id"`
|
||||
StepNumber int `gorm:"not null" json:"step_number"`
|
||||
StepName *string `gorm:"size:100" json:"step_name"`
|
||||
StepType *string `gorm:"size:20" json:"step_type"`
|
||||
ApproverID *int `json:"approver_id"`
|
||||
ApproverRole *string `gorm:"size:20" json:"approver_role"`
|
||||
ActualApproverID *int `json:"actual_approver_id"`
|
||||
Action *string `gorm:"size:20" json:"action"`
|
||||
Comment *string `gorm:"type:text" json:"comment"`
|
||||
TransferFrom *int `json:"transfer_from"`
|
||||
TransferReason *string `gorm:"type:text" json:"transfer_reason"`
|
||||
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"`
|
||||
CompletedAt *time.Time `json:"completed_at"`
|
||||
IsTimeout *bool `json:"is_timeout"`
|
||||
TimeoutHandledAt *time.Time `json:"timeout_handled_at"`
|
||||
}
|
||||
|
||||
func (TicketApproval) TableName() string { return "ticket_approvals" }
|
||||
|
||||
// ==================== TicketSQLItem ====================
|
||||
|
||||
type TicketSQLItem struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
TicketID int `gorm:"not null" json:"ticket_id"`
|
||||
Seq int `gorm:"not null" json:"seq"`
|
||||
SQLText string `gorm:"type:text;not null" json:"sql_text"`
|
||||
SQLType *string `gorm:"size:20" json:"sql_type"`
|
||||
Status *string `gorm:"size:20;default:pending" json:"status"`
|
||||
AffectedRows *int `gorm:"default:0" json:"affected_rows"`
|
||||
DurationMs *int `gorm:"default:0" json:"duration_ms"`
|
||||
ErrorMessage *string `gorm:"type:text" json:"error_message"`
|
||||
StartedAt *time.Time `json:"started_at"`
|
||||
FinishedAt *time.Time `json:"finished_at"`
|
||||
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
}
|
||||
|
||||
func (TicketSQLItem) TableName() string { return "ticket_sql_items" }
|
||||
|
||||
// ==================== AuditRule ====================
|
||||
|
||||
type AuditRule struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
Name string `gorm:"size:100;not null" json:"name"`
|
||||
Desc *string `gorm:"type:text" json:"description"`
|
||||
RuleType string `gorm:"size:50;not null" json:"rule_type"`
|
||||
Severity *string `gorm:"size:20" json:"severity"`
|
||||
DBType *string `gorm:"size:20" json:"db_type"`
|
||||
Pattern *string `gorm:"type:text" json:"pattern"`
|
||||
IsEnabled *bool `json:"is_enabled"`
|
||||
Message string `gorm:"size:500;not null" json:"message"`
|
||||
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"`
|
||||
Value *string `gorm:"size:255" json:"value"`
|
||||
Code *string `gorm:"size:50" json:"code"`
|
||||
ConfigJSON *string `gorm:"type:text;column:config_json" json:"config_json"`
|
||||
}
|
||||
|
||||
func (AuditRule) TableName() string { return "audit_rules" }
|
||||
|
||||
// ==================== AuditLog ====================
|
||||
|
||||
type AuditLog struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
UserID int `gorm:"not null" json:"user_id"`
|
||||
Action string `gorm:"size:50;not null" json:"action"`
|
||||
TargetType string `gorm:"size:50;not null" json:"target_type"`
|
||||
TargetID *int `json:"target_id"`
|
||||
Detail *string `gorm:"type:text" json:"detail"`
|
||||
IPAddress *string `gorm:"size:50" json:"ip_address"`
|
||||
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
Username *string `gorm:"size:50" json:"username"`
|
||||
DBType *string `gorm:"size:20" json:"db_type"`
|
||||
DatabaseName *string `gorm:"size:100" json:"database_name"`
|
||||
InstanceName *string `gorm:"size:100" json:"instance_name"`
|
||||
ExecutionTimeMs *int `json:"execution_time_ms"`
|
||||
RowsAffected *int `json:"rows_affected"`
|
||||
ResultStatus *string `gorm:"size:20" json:"result_status"`
|
||||
QueryContent *string `gorm:"type:text" json:"query_content"`
|
||||
UserAgent *string `gorm:"size:200" json:"user_agent"`
|
||||
IsRisky *bool `gorm:"default:false" json:"is_risky"`
|
||||
}
|
||||
|
||||
func (AuditLog) TableName() string { return "audit_logs" }
|
||||
|
||||
// ==================== QueryHistory ====================
|
||||
|
||||
type QueryHistory struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
UserID int `gorm:"not null" json:"user_id"`
|
||||
Username string `gorm:"size:100;not null" json:"username"`
|
||||
InstanceID int `gorm:"not null" json:"instance_id"`
|
||||
InstanceName string `gorm:"size:100;not null" json:"instance_name"`
|
||||
DBType string `gorm:"size:20;not null" json:"db_type"`
|
||||
DatabaseName string `gorm:"size:100;not null" json:"database_name"`
|
||||
QueryContent string `gorm:"type:text;not null" json:"query_content"`
|
||||
QueryType string `gorm:"size:50;not null" json:"query_type"`
|
||||
ExecutionTimeMs int `gorm:"not null" json:"execution_time_ms"`
|
||||
ResultRows int `gorm:"not null" json:"result_rows"`
|
||||
IsSuccess bool `gorm:"not null" json:"is_success"`
|
||||
ErrorMessage *string `gorm:"type:text" json:"error_message"`
|
||||
IsFavorite bool `gorm:"not null" json:"is_favorite"`
|
||||
Note string `gorm:"type:text;not null" json:"note"`
|
||||
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
}
|
||||
|
||||
func (QueryHistory) TableName() string { return "query_histories" }
|
||||
|
||||
// ==================== Workflow ====================
|
||||
|
||||
type WorkflowDefinition struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
Name string `gorm:"size:100;not null" json:"name"`
|
||||
Description *string `gorm:"type:text" json:"description"`
|
||||
Category *string `gorm:"size:50" json:"category"`
|
||||
IsDefault *bool `json:"is_default"`
|
||||
IsActive *bool `json:"is_active"`
|
||||
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"`
|
||||
CreatedBy *int `json:"created_by"`
|
||||
FlowConfig *string `gorm:"type:json" json:"flow_config"`
|
||||
TriggerConditions *string `gorm:"type:json" json:"trigger_conditions"`
|
||||
}
|
||||
|
||||
func (WorkflowDefinition) TableName() string { return "workflow_definitions" }
|
||||
|
||||
type WorkflowStep struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
WorkflowID int `gorm:"not null" json:"workflow_id"`
|
||||
StepNumber int `gorm:"not null" json:"step_number"`
|
||||
Name string `gorm:"size:100;not null" json:"name"`
|
||||
Description *string `gorm:"type:text" json:"description"`
|
||||
StepType string `gorm:"size:20;not null" json:"step_type"`
|
||||
ApproverRole *string `gorm:"size:20" json:"approver_role"`
|
||||
ApproverIDs *string `gorm:"type:json" json:"approver_ids"`
|
||||
ApproverAssignment *string `gorm:"type:json" json:"approver_assignment"`
|
||||
IsRequired *bool `json:"is_required"`
|
||||
TimeoutHours *int `json:"timeout_hours"`
|
||||
AutoApproveOnTimeout *bool `json:"auto_approve_on_timeout"`
|
||||
EntryConditions *string `gorm:"type:json" json:"entry_conditions"`
|
||||
TransitionConditions *string `gorm:"type:json" json:"transition_conditions"`
|
||||
FieldPermissions *string `gorm:"type:json" json:"field_permissions"`
|
||||
}
|
||||
|
||||
func (WorkflowStep) TableName() string { return "workflow_steps" }
|
||||
|
||||
type WorkflowVersion struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
WorkflowID int `gorm:"not null" json:"workflow_id"`
|
||||
VersionNumber int `gorm:"not null" json:"version_number"`
|
||||
VersionName *string `gorm:"size:100" json:"version_name"`
|
||||
IsActive *bool `json:"is_active"`
|
||||
StepsSnapshot *string `gorm:"type:json" json:"steps_snapshot"`
|
||||
FlowConfigSnapshot *string `gorm:"type:json" json:"flow_config_snapshot"`
|
||||
ChangeSummary *string `gorm:"type:text" json:"change_summary"`
|
||||
CreatedBy *int `json:"created_by"`
|
||||
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
}
|
||||
|
||||
func (WorkflowVersion) TableName() string { return "workflow_versions" }
|
||||
|
||||
type WorkflowExecutionLog struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
WorkflowID int `gorm:"not null" json:"workflow_id"`
|
||||
TicketID *int `json:"ticket_id"`
|
||||
StepID *int `json:"step_id"`
|
||||
ApprovalID *int `json:"approval_id"`
|
||||
EventType string `gorm:"size:50;not null" json:"event_type"`
|
||||
EventDescription *string `gorm:"type:text" json:"event_description"`
|
||||
ActorID *int `json:"actor_id"`
|
||||
ActorName *string `gorm:"size:100" json:"actor_name"`
|
||||
ContextData *string `gorm:"type:json" json:"context_data"`
|
||||
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
}
|
||||
|
||||
func (WorkflowExecutionLog) TableName() string { return "workflow_execution_logs" }
|
||||
|
||||
// ==================== Announcement ====================
|
||||
|
||||
type Announcement struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
Title string `gorm:"size:200;not null" json:"title"`
|
||||
Content string `gorm:"type:text;not null" json:"content"`
|
||||
IsPublished *bool `json:"is_published"`
|
||||
PublishedAt *time.Time `json:"published_at"`
|
||||
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"`
|
||||
}
|
||||
|
||||
func (Announcement) TableName() string { return "announcements" }
|
||||
|
||||
// ==================== InstanceGroup ====================
|
||||
|
||||
type InstanceGroup struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
Name string `gorm:"size:100;not null" json:"name"`
|
||||
Description *string `gorm:"type:text" json:"description"`
|
||||
DBType string `gorm:"size:20;not null" json:"db_type"`
|
||||
Permissions *string `gorm:"type:text" json:"permissions"`
|
||||
IsActive *bool `json:"is_active"`
|
||||
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"`
|
||||
WorkflowID *int `json:"workflow_id"`
|
||||
AccessType *string `gorm:"size:20;default:readonly" json:"access_type"`
|
||||
AllowedDatabases *string `gorm:"type:text" json:"allowed_databases"`
|
||||
}
|
||||
|
||||
func (InstanceGroup) TableName() string { return "instance_groups" }
|
||||
|
||||
type InstanceGroupMember struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
GroupID int `gorm:"not null" json:"group_id"`
|
||||
InstanceID int `gorm:"not null" json:"instance_id"`
|
||||
AccessType string `gorm:"default:readonly" json:"access_type"`
|
||||
}
|
||||
|
||||
func (InstanceGroupMember) TableName() string { return "instance_group_members" }
|
||||
|
||||
// ==================== LDAP Config ====================
|
||||
|
||||
type LDAPConfig struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
LDAPHost string `gorm:"size:200;not null" json:"ldap_host"`
|
||||
LDAPPort *int `json:"ldap_port"`
|
||||
UseLDAPS *bool `json:"use_ldaps"`
|
||||
AdminDN string `gorm:"size:500;not null" json:"admin_dn"`
|
||||
AdminPassword string `gorm:"size:500;not null" json:"admin_password"`
|
||||
SearchFilter *string `gorm:"size:500" json:"search_filter"`
|
||||
BaseDN string `gorm:"size:500;not null" json:"base_dn"`
|
||||
UserMapping *string `gorm:"type:text" json:"user_mapping"`
|
||||
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"`
|
||||
}
|
||||
|
||||
func (LDAPConfig) TableName() string { return "ldap_config" }
|
||||
|
||||
// ==================== Notification ====================
|
||||
|
||||
type NotificationChannel struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
Name string `gorm:"size:100;not null" json:"name"`
|
||||
ChannelType string `gorm:"size:30;not null" json:"channel_type"`
|
||||
Config string `gorm:"type:text;not null" json:"config"`
|
||||
IsEnabled *bool `json:"is_enabled"`
|
||||
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"`
|
||||
}
|
||||
|
||||
func (NotificationChannel) TableName() string { return "notification_channels" }
|
||||
|
||||
type NotificationTemplate struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
Name string `gorm:"size:100;not null" json:"name"`
|
||||
EventType string `gorm:"size:50;not null" json:"event_type"`
|
||||
ChannelType string `gorm:"size:30;not null" json:"channel_type"`
|
||||
TitleTemplate *string `gorm:"type:text" json:"title_template"`
|
||||
BodyTemplate *string `gorm:"type:text" json:"body_template"`
|
||||
IsEnabled *bool `json:"is_enabled"`
|
||||
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
}
|
||||
|
||||
func (NotificationTemplate) TableName() string { return "notification_templates" }
|
||||
|
||||
// ==================== Other Models ====================
|
||||
|
||||
type SystemSetting struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
Key string `gorm:"size:100;not null" json:"key"`
|
||||
Value string `gorm:"type:text;not null" json:"value"`
|
||||
ValueType string `gorm:"size:20;not null" json:"value_type"`
|
||||
Group string `gorm:"size:50;not null" json:"group"`
|
||||
Label string `gorm:"size:100;not null" json:"label"`
|
||||
Desc *string `gorm:"type:text" json:"description"`
|
||||
DefaultValue *string `gorm:"type:text" json:"default_value"`
|
||||
SortOrder int `gorm:"not null" json:"sort_order"`
|
||||
UpdatedAt *time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (SystemSetting) TableName() string { return "system_settings" }
|
||||
|
||||
type OperationLog struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
UserID *int `json:"user_id"`
|
||||
Username *string `gorm:"size:50" json:"username"`
|
||||
Action string `gorm:"size:50;not null" json:"action"`
|
||||
ResourceType *string `gorm:"size:50" json:"resource_type"`
|
||||
ResourceID *int `json:"resource_id"`
|
||||
Detail *string `gorm:"type:text" json:"detail"`
|
||||
IPAddress *string `gorm:"size:50" json:"ip_address"`
|
||||
UserAgent *string `gorm:"size:255" json:"user_agent"`
|
||||
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
}
|
||||
|
||||
func (OperationLog) TableName() string { return "operation_logs" }
|
||||
|
||||
type MaskingRule struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
InstanceID int `gorm:"not null" json:"instance_id"`
|
||||
Database string `gorm:"size:100;not null" json:"database"`
|
||||
TblName string `gorm:"size:100;not null;column:table_name" json:"table_name"`
|
||||
ColumnName string `gorm:"size:100;not null" json:"column_name"`
|
||||
MaskType string `gorm:"size:30;not null" json:"mask_type"`
|
||||
MaskConfig *string `gorm:"type:text" json:"mask_config"`
|
||||
IsEnabled *bool `json:"is_enabled"`
|
||||
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"`
|
||||
}
|
||||
|
||||
func (MaskingRule) TableName() string { return "masking_rules" }
|
||||
|
||||
type Backup struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
InstanceID int `gorm:"not null" json:"instance_id"`
|
||||
Title string `gorm:"size:200;not null" json:"title"`
|
||||
Database string `gorm:"size:100;not null" json:"database"`
|
||||
Filename string `gorm:"size:500;not null" json:"filename"`
|
||||
SizeBytes *int64 `json:"size_bytes"`
|
||||
Status *string `gorm:"size:20" json:"status"`
|
||||
CreatedBy *int `json:"created_by"`
|
||||
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
CompletedAt *time.Time `json:"completed_at"`
|
||||
Remark *string `gorm:"type:text" json:"remark"`
|
||||
}
|
||||
|
||||
func (Backup) TableName() string { return "backups" }
|
||||
|
||||
type SchemaRevision struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
InstanceID int `gorm:"not null" json:"instance_id"`
|
||||
Database string `gorm:"size:100;not null" json:"database"`
|
||||
Revision string `gorm:"size:64;not null" json:"revision"`
|
||||
DDLContent *string `gorm:"type:text" json:"ddl_content"`
|
||||
Checksum string `gorm:"size:64;not null" json:"checksum"`
|
||||
AppliedBy *int `json:"applied_by"`
|
||||
AppliedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"applied_at"`
|
||||
Status *string `gorm:"size:20" json:"status"`
|
||||
}
|
||||
|
||||
func (SchemaRevision) TableName() string { return "schema_revisions" }
|
||||
|
||||
type SlowLog struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
InstanceID int `gorm:"not null" json:"instance_id"`
|
||||
Database *string `gorm:"size:100" json:"database"`
|
||||
SQLDigest *string `gorm:"size:64" json:"sql_digest"`
|
||||
SQLText *string `gorm:"type:text" json:"sql_text"`
|
||||
ExecutionCount *int `json:"execution_count"`
|
||||
AvgTimeMs *int `json:"avg_time_ms"`
|
||||
MaxTimeMs *int `json:"max_time_ms"`
|
||||
RowsExamined *int `json:"rows_examined"`
|
||||
RowsSent *int `json:"rows_sent"`
|
||||
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
}
|
||||
|
||||
func (SlowLog) TableName() string { return "slow_logs" }
|
||||
|
||||
type ScheduledTask struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
Name string `gorm:"size:100;not null" json:"name"`
|
||||
Description *string `gorm:"type:text" json:"description"`
|
||||
TaskSQLType string `gorm:"size:20;not null" json:"task_sql_type"`
|
||||
InstanceID int `gorm:"not null" json:"instance_id"`
|
||||
TargetDB *string `gorm:"size:100" json:"target_db"`
|
||||
TargetTable *string `gorm:"size:100" json:"target_table"`
|
||||
SQLContent string `gorm:"type:text;not null" json:"sql_content"`
|
||||
CronExpression string `gorm:"size:50;not null" json:"cron_expression"`
|
||||
IsEnabled *bool `json:"is_enabled"`
|
||||
LastRunAt *time.Time `json:"last_run_at"`
|
||||
LastRunStatus *string `gorm:"size:20" json:"last_run_status"`
|
||||
LastRunMessage *string `gorm:"type:text" json:"last_run_message"`
|
||||
NextRunAt *time.Time `json:"next_run_at"`
|
||||
RunCount *int `json:"run_count"`
|
||||
CreatedBy *int `json:"created_by"`
|
||||
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"`
|
||||
}
|
||||
|
||||
func (ScheduledTask) TableName() string { return "scheduled_tasks" }
|
||||
|
||||
type ScheduledTaskLog struct {
|
||||
ID int `gorm:"primaryKey" json:"id"`
|
||||
TaskID int `gorm:"not null" json:"task_id"`
|
||||
Status string `gorm:"size:20;not null" json:"status"`
|
||||
SQLContent *string `gorm:"type:text" json:"sql_content"`
|
||||
AffectedRows *int `json:"affected_rows"`
|
||||
DurationMs *int `json:"duration_ms"`
|
||||
ErrorMessage *string `gorm:"type:text" json:"error_message"`
|
||||
StartedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"started_at"`
|
||||
FinishedAt *time.Time `json:"finished_at"`
|
||||
}
|
||||
|
||||
func (ScheduledTaskLog) TableName() string { return "scheduled_task_logs" }
|
||||
|
||||
type UserGroup struct {
|
||||
UserID int `gorm:"primaryKey" json:"user_id"`
|
||||
GroupID int `gorm:"primaryKey" json:"group_id"`
|
||||
Permissions *string `gorm:"type:text" json:"permissions"`
|
||||
}
|
||||
|
||||
func (UserGroup) TableName() string { return "user_groups" }
|
||||
|
||||
// ==================== DTO ====================
|
||||
|
||||
type LoginRequest struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
type LoginResponse struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
TokenType string `json:"token_type"`
|
||||
User User `json:"user"`
|
||||
}
|
||||
|
||||
type TicketStatistics struct {
|
||||
Total int `json:"total"`
|
||||
Pending int `json:"pending"`
|
||||
Reviewing int `json:"reviewing"`
|
||||
Executing int `json:"executing"`
|
||||
Completed int `json:"completed"`
|
||||
Failed int `json:"failed"`
|
||||
Rejected int `json:"rejected"`
|
||||
}
|
||||
|
||||
// DB is the global database instance
|
||||
var DB *gorm.DB
|
||||
@@ -0,0 +1,145 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gorm.io/gorm"
|
||||
"sql-platform/internal/middleware"
|
||||
"sql-platform/internal/model"
|
||||
)
|
||||
|
||||
type AuthService struct {
|
||||
DB *gorm.DB
|
||||
}
|
||||
|
||||
func NewAuthService(db *gorm.DB) *AuthService {
|
||||
return &AuthService{DB: db}
|
||||
}
|
||||
|
||||
// Login authenticates a user and returns a JWT token
|
||||
func (s *AuthService) Login(username, password string) (*model.User, string, error) {
|
||||
var user model.User
|
||||
if err := s.DB.Where("username = ?", username).First(&user).Error; err != nil {
|
||||
return nil, "", errors.New("invalid username or password")
|
||||
}
|
||||
|
||||
if !user.IsActive {
|
||||
return nil, "", errors.New("account is disabled")
|
||||
}
|
||||
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.HashedPassword), []byte(password)); err != nil {
|
||||
return nil, "", errors.New("invalid username or password")
|
||||
}
|
||||
|
||||
token, err := middleware.GenerateToken(user.ID, user.Username, user.Role)
|
||||
if err != nil {
|
||||
return nil, "", errors.New("failed to generate token")
|
||||
}
|
||||
|
||||
// Update last login
|
||||
now := time.Now()
|
||||
user.LastLogin = &now
|
||||
s.DB.Model(&user).Update("last_login", now)
|
||||
|
||||
return &user, token, nil
|
||||
}
|
||||
|
||||
// Register creates a new user
|
||||
func (s *AuthService) Register(username, displayName, email, phone, password, role string) (*model.User, error) {
|
||||
// Check if username already exists
|
||||
var count int64
|
||||
s.DB.Model(&model.User{}).Where("username = ?", username).Count(&count)
|
||||
if count > 0 {
|
||||
return nil, errors.New("username already exists")
|
||||
}
|
||||
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to hash password")
|
||||
}
|
||||
|
||||
if role == "" {
|
||||
role = "developer"
|
||||
}
|
||||
|
||||
user := model.User{
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
Email: email,
|
||||
Phone: phone,
|
||||
HashedPassword: string(hashedPassword),
|
||||
Role: role,
|
||||
IsActive: true,
|
||||
}
|
||||
|
||||
if err := s.DB.Create(&user).Error; err != nil {
|
||||
return nil, errors.New("failed to create user")
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// GetUserByID retrieves a user by ID
|
||||
func (s *AuthService) GetUserByID(id uint) (*model.User, error) {
|
||||
var user model.User
|
||||
if err := s.DB.First(&user, id).Error; err != nil {
|
||||
return nil, errors.New("user not found")
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// ListUsers returns all users
|
||||
func (s *AuthService) ListUsers(page, pageSize int) ([]model.User, int64, error) {
|
||||
var users []model.User
|
||||
var total int64
|
||||
|
||||
db := s.DB.Model(&model.User{})
|
||||
db.Count(&total)
|
||||
|
||||
offset := (page - 1) * pageSize
|
||||
if err := db.Offset(offset).Limit(pageSize).Find(&users).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return users, total, nil
|
||||
}
|
||||
|
||||
// UpdateUser updates a user's info
|
||||
func (s *AuthService) UpdateUser(id uint, updates map[string]interface{}) error {
|
||||
return s.DB.Model(&model.User{}).Where("id = ?", id).Updates(updates).Error
|
||||
}
|
||||
|
||||
// DeleteUser soft-deletes a user
|
||||
func (s *AuthService) DeleteUser(id uint) error {
|
||||
return s.DB.Delete(&model.User{}, id).Error
|
||||
}
|
||||
|
||||
// ChangePassword changes a user's password
|
||||
func (s *AuthService) ChangePassword(id uint, oldPassword, newPassword string) error {
|
||||
var user model.User
|
||||
if err := s.DB.First(&user, id).Error; err != nil {
|
||||
return errors.New("user not found")
|
||||
}
|
||||
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.HashedPassword), []byte(oldPassword)); err != nil {
|
||||
return errors.New("incorrect current password")
|
||||
}
|
||||
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return errors.New("failed to hash password")
|
||||
}
|
||||
|
||||
return s.DB.Model(&user).Update("hashed_password", string(hashedPassword)).Error
|
||||
}
|
||||
|
||||
// ResetPassword resets a user's password (admin only)
|
||||
func (s *AuthService) ResetPassword(id uint, newPassword string) error {
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return errors.New("failed to hash password")
|
||||
}
|
||||
return s.DB.Model(&model.User{}).Where("id = ?", id).Update("hashed_password", string(hashedPassword)).Error
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"sql-platform/internal/model"
|
||||
)
|
||||
|
||||
type InstanceService struct {
|
||||
DB *gorm.DB
|
||||
}
|
||||
|
||||
func NewInstanceService(db *gorm.DB) *InstanceService {
|
||||
return &InstanceService{DB: db}
|
||||
}
|
||||
|
||||
// CreateInstance creates a new database instance
|
||||
func (s *InstanceService) CreateInstance(instance *model.Instance) error {
|
||||
return s.DB.Create(instance).Error
|
||||
}
|
||||
|
||||
// GetInstanceByID retrieves an instance by ID
|
||||
func (s *InstanceService) GetInstanceByID(id uint) (*model.Instance, error) {
|
||||
var instance model.Instance
|
||||
if err := s.DB.First(&instance, id).Error; err != nil {
|
||||
return nil, errors.New("instance not found")
|
||||
}
|
||||
return &instance, nil
|
||||
}
|
||||
|
||||
// ListInstances returns paginated instances
|
||||
func (s *InstanceService) ListInstances(page, pageSize int, dbType, env string) ([]model.Instance, int64, error) {
|
||||
var instances []model.Instance
|
||||
var total int64
|
||||
|
||||
db := s.DB.Model(&model.Instance{})
|
||||
if dbType != "" {
|
||||
db = db.Where("db_type = ?", dbType)
|
||||
}
|
||||
if env != "" {
|
||||
db = db.Where("env = ?", env)
|
||||
}
|
||||
|
||||
db.Count(&total)
|
||||
offset := (page - 1) * pageSize
|
||||
if err := db.Offset(offset).Limit(pageSize).Order("created_at DESC").Find(&instances).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return instances, total, nil
|
||||
}
|
||||
|
||||
// UpdateInstance updates an instance
|
||||
func (s *InstanceService) UpdateInstance(id uint, updates map[string]interface{}) error {
|
||||
result := s.DB.Model(&model.Instance{}).Where("id = ?", id).Updates(updates)
|
||||
if result.RowsAffected == 0 {
|
||||
return errors.New("instance not found")
|
||||
}
|
||||
return result.Error
|
||||
}
|
||||
|
||||
// DeleteInstance soft-deletes an instance
|
||||
func (s *InstanceService) DeleteInstance(id uint) error {
|
||||
return s.DB.Delete(&model.Instance{}, id).Error
|
||||
}
|
||||
|
||||
// TestConnection tests the database connection
|
||||
func (s *InstanceService) TestConnection(instance *model.Instance) error {
|
||||
// TODO: Implement actual connection test based on db_type
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListInstancesByIDs returns instances matching the given IDs
|
||||
func (s *InstanceService) ListInstancesByIDs(ids []uint) ([]model.Instance, error) {
|
||||
var instances []model.Instance
|
||||
if err := s.DB.Where("id IN ?", ids).Find(&instances).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return instances, nil
|
||||
}
|
||||
|
||||
// GetInstanceGroups returns all instance groups
|
||||
func (s *InstanceService) GetInstanceGroups() ([]model.InstanceGroup, error) {
|
||||
var groups []model.InstanceGroup
|
||||
err := s.DB.Find(&groups).Error
|
||||
return groups, err
|
||||
}
|
||||
|
||||
// CreateInstanceGroup creates a new instance group
|
||||
func (s *InstanceService) CreateInstanceGroup(group *model.InstanceGroup) error {
|
||||
return s.DB.Create(group).Error
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"sql-platform/internal/model"
|
||||
)
|
||||
|
||||
type TicketService struct {
|
||||
DB *gorm.DB
|
||||
}
|
||||
|
||||
func NewTicketService(db *gorm.DB) *TicketService {
|
||||
return &TicketService{DB: db}
|
||||
}
|
||||
|
||||
// CreateTicket creates a new ticket
|
||||
func (s *TicketService) CreateTicket(ticket *model.Ticket) error {
|
||||
if ticket.TicketNo == "" {
|
||||
ticket.TicketNo = s.generateTicketNo()
|
||||
}
|
||||
if ticket.CreateTime.IsZero() {
|
||||
ticket.CreateTime = time.Now()
|
||||
}
|
||||
if ticket.Status == "" {
|
||||
ticket.Status = "pending"
|
||||
}
|
||||
return s.DB.Create(ticket).Error
|
||||
}
|
||||
|
||||
// GetTicketByID retrieves a ticket by ID
|
||||
func (s *TicketService) GetTicketByID(id uint) (*model.Ticket, error) {
|
||||
var ticket model.Ticket
|
||||
if err := s.DB.First(&ticket, id).Error; err != nil {
|
||||
return nil, errors.New("ticket not found")
|
||||
}
|
||||
return &ticket, nil
|
||||
}
|
||||
|
||||
// ListTickets returns paginated tickets with filters
|
||||
func (s *TicketService) ListTickets(page, pageSize int, status, priority string, applicantID uint) ([]model.Ticket, int64, error) {
|
||||
var tickets []model.Ticket
|
||||
var total int64
|
||||
|
||||
db := s.DB.Model(&model.Ticket{})
|
||||
if status != "" {
|
||||
db = db.Where("status = ?", status)
|
||||
}
|
||||
if priority != "" {
|
||||
db = db.Where("priority = ?", priority)
|
||||
}
|
||||
if applicantID > 0 {
|
||||
db = db.Where("applicant_id = ?", applicantID)
|
||||
}
|
||||
|
||||
db.Count(&total)
|
||||
offset := (page - 1) * pageSize
|
||||
if err := db.Offset(offset).Limit(pageSize).Order("create_time DESC").Find(&tickets).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return tickets, total, nil
|
||||
}
|
||||
|
||||
// UpdateTicketStatus updates a ticket's status
|
||||
func (s *TicketService) UpdateTicketStatus(id uint, status string, updaterID uint) error {
|
||||
updates := map[string]interface{}{
|
||||
"status": status,
|
||||
}
|
||||
now := time.Now()
|
||||
switch status {
|
||||
case "approved":
|
||||
updates["approver_id"] = updaterID
|
||||
updates["review_time"] = now
|
||||
case "executing", "completed", "failed":
|
||||
updates["execute_time"] = now
|
||||
}
|
||||
|
||||
result := s.DB.Model(&model.Ticket{}).Where("id = ?", id).Updates(updates)
|
||||
if result.RowsAffected == 0 {
|
||||
return errors.New("ticket not found")
|
||||
}
|
||||
return result.Error
|
||||
}
|
||||
|
||||
// ApproveTicket approves a ticket
|
||||
func (s *TicketService) ApproveTicket(id, approverID uint, comment string) error {
|
||||
return s.UpdateTicketStatus(id, "approved", approverID)
|
||||
}
|
||||
|
||||
// RejectTicket rejects a ticket
|
||||
func (s *TicketService) RejectTicket(id, approverID uint, comment string) error {
|
||||
return s.UpdateTicketStatus(id, "rejected", approverID)
|
||||
}
|
||||
|
||||
// GetTicketSQLItems returns SQL items for a ticket
|
||||
func (s *TicketService) GetTicketSQLItems(ticketID uint) ([]model.TicketSQLItem, error) {
|
||||
var items []model.TicketSQLItem
|
||||
err := s.DB.Where("ticket_id = ?", ticketID).Order("seq ASC").Find(&items).Error
|
||||
return items, err
|
||||
}
|
||||
|
||||
// CreateTicketSQLItem creates a SQL item for a ticket
|
||||
func (s *TicketService) CreateTicketSQLItem(item *model.TicketSQLItem) error {
|
||||
return s.DB.Create(item).Error
|
||||
}
|
||||
|
||||
// GetTicketApprovals returns approval records for a ticket
|
||||
func (s *TicketService) GetTicketApprovals(ticketID uint) ([]model.TicketApproval, error) {
|
||||
var approvals []model.TicketApproval
|
||||
err := s.DB.Where("ticket_id = ?", ticketID).Order("step_number ASC").Find(&approvals).Error
|
||||
return approvals, err
|
||||
}
|
||||
|
||||
// DeleteTicket soft-deletes a ticket
|
||||
func (s *TicketService) DeleteTicket(id uint) error {
|
||||
return s.DB.Delete(&model.Ticket{}, id).Error
|
||||
}
|
||||
|
||||
// generateTicketNo generates a unique ticket number
|
||||
func (s *TicketService) generateTicketNo() string {
|
||||
now := time.Now()
|
||||
var count int64
|
||||
s.DB.Model(&model.Ticket{}).Where("DATE(create_time) = DATE(?)", now).Count(&count)
|
||||
return fmt.Sprintf("TK-%s-%04d", now.Format("20060102"), count+1)
|
||||
}
|
||||
Reference in new issue
Block a user