Documentation
¶
Overview ¶
Package service 业务服务层:模型定义 + 持久化 + 任务调度 + CLI。 对外通过 Web 模式(Gin 托管前端 SPA)与 CLI 模式提供能力。
Index ¶
- Constants
- Variables
- func FindConfigFile(explicit string) string
- func IsArtifactLogicalPath(p string) bool
- func NormalizeUser(u string) string
- func SaveAIProviders(providers []AIProviderItem) error
- func SetProvidersDataDir(dir string)
- func WithLang(ctx context.Context, lang string) context.Context
- func WithUser(ctx context.Context, user string) context.Context
- type AIConfig
- type AIModelInfo
- type AIProvider
- type AIProviderConfig
- type AIProviderItem
- type AIProviderStored
- type AISession
- type AISessionRecord
- type AIStatus
- type AppConfig
- type CLIConfig
- type CompareOptions
- type CompareResult
- type ConfigInfo
- type ConnHooks
- type ConnInfo
- type ConnProvider
- type ConnRecord
- type ConnSource
- type Contributor
- type ContributorImportRequest
- type ContributorRequest
- type ContributorResult
- type CreateSnapshotOptions
- type DBConnInfo
- type DataEntry
- type DataPackage
- type DataPrepareRequest
- type DataPreparer
- type DictionaryOptions
- type DirBrowseResult
- type DirConfig
- type DirEntry
- type ExecutionRecord
- type ExportFormat
- type ExportOptions
- type ImportOptions
- type LibraryOptions
- type MigrateOptions
- type ObjectDDLResult
- type PersistMgr
- func (p *PersistMgr) AISessionExists(sessionID string) bool
- func (p *PersistMgr) AddFavorite(user string, f *SQLFavorite) error
- func (p *PersistMgr) AddSQLHistory(user string, item SQLHistoryItem) error
- func (p *PersistMgr) AppendSQLAudit(user string, entry SQLAuditEntry) error
- func (p *PersistMgr) BaseDir() string
- func (p *PersistMgr) ClearSQLHistory(user, connID string) error
- func (p *PersistMgr) Close() error
- func (p *PersistMgr) CompareDir() string
- func (p *PersistMgr) DeleteAISession(user, sessionID string) error
- func (p *PersistMgr) DeleteAISessionByTab(user, connID, tabID string) error
- func (p *PersistMgr) DeleteAISessionsByConn(user, connID string) error
- func (p *PersistMgr) DeleteAllUsersAISessionsByConn(connID string) error
- func (p *PersistMgr) DeleteAllUsersWorkspacesByConn(connID string) error
- func (p *PersistMgr) DeleteConn(key string) error
- func (p *PersistMgr) DeleteFavorite(user, id string) error
- func (p *PersistMgr) DeleteHistory(id string) error
- func (p *PersistMgr) DeleteSnapshot(id string) error
- func (p *PersistMgr) DeleteTask(taskID string) error
- func (p *PersistMgr) DeleteWorkspace(user, connID string) error
- func (p *PersistMgr) ExportDir() string
- func (p *PersistMgr) GetConn(key string) (ConnRecord, bool)
- func (p *PersistMgr) GetHistory(id string) (ExecutionRecord, error)
- func (p *PersistMgr) GetLastUsed(taskType string) *TaskConfig
- func (p *PersistMgr) GetMeta(key string) (string, bool, error)
- func (p *PersistMgr) GetTask(id string) (TaskConfig, bool)
- func (p *PersistMgr) ListAISessions(user, connID, tabID string) []AISessionRecord
- func (p *PersistMgr) ListFavorites(user string) []*SQLFavorite
- func (p *PersistMgr) ListSQLAudit(user, connID string, limit, offset int) ([]SQLAuditEntry, error)
- func (p *PersistMgr) ListSQLHistory(user, connID string) []SQLHistoryItem
- func (p *PersistMgr) ListSnapshots(connID string) ([]SnapshotInfo, error)
- func (p *PersistMgr) LoadAISession(user, sessionID string) (AISessionRecord, bool)
- func (p *PersistMgr) LoadConns() map[string]ConnRecord
- func (p *PersistMgr) LoadHistory(taskType, taskConfigID string) []ExecutionRecord
- func (p *PersistMgr) LoadTasks() []TaskConfig
- func (p *PersistMgr) LoadWebAccess() (WebAccessInfo, bool)
- func (p *PersistMgr) LoadWorkspace(user, connID string) (WorkspaceState, bool)
- func (p *PersistMgr) MarkLastUsed(taskID, taskType string) error
- func (p *PersistMgr) PurgeExcessAISessions(maxPerConn, keepDays int) (int64, error)
- func (p *PersistMgr) RemoveArtifact(outputPath string)
- func (p *PersistMgr) RenameFavorite(user, id, title string) error
- func (p *PersistMgr) SaveAISession(user string, rec AISessionRecord) error
- func (p *PersistMgr) SaveConn(rec ConnRecord) (ConnRecord, error)
- func (p *PersistMgr) SaveHistory(record ExecutionRecord) error
- func (p *PersistMgr) SaveTask(task TaskConfig) error
- func (p *PersistMgr) SaveWebAccess(info WebAccessInfo) error
- func (p *PersistMgr) SaveWorkspace(user, connID string, state WorkspaceState) error
- func (p *PersistMgr) SetMeta(key, value string) error
- func (p *PersistMgr) SetSnapshotsExternal(v bool)
- func (p *PersistMgr) SnapshotDir() string
- func (p *PersistMgr) TempDir() string
- func (p *PersistMgr) UpdateDirs(dirs ResolvedDirs) error
- func (p *PersistMgr) UploadDir() string
- func (p *PersistMgr) UpsertSnapshot(info SnapshotInfo) error
- type ProgressFunc
- type ProgressInfo
- type QueryHooks
- type ResetMode
- type ResolvedDirs
- type SQLAuditEntry
- type SQLFavorite
- type SQLHistoryItem
- type Service
- func (s *Service) AIChat(ctx context.Context, sessionID, action, task, msgID string) (string, llm.Usage, bool, error)
- func (s *Service) AIChatStream(ctx context.Context, sessionID, action, task, msgID string, ...) (llm.Usage, bool, error)
- func (s *Service) AIChatStreamWithFallback(ctx context.Context, lang, sessionID, action, task, msgID string, ...) (llm.Usage, bool, error)
- func (s *Service) AIDeleteSession(user, sessionID string) error
- func (s *Service) AIDeleteSessionByTab(user, connID, tabID string)
- func (s *Service) AIEnabled() bool
- func (s *Service) AIListSessions(user, connID, tabID string) []AISessionRecord
- func (s *Service) AILoadSessionHistory(user, sessionID string) []AISessionRecord
- func (s *Service) AINewSession(ctx context.Context, lang, connKey, dbName, tabID string, ...) (*AISession, error)
- func (s *Service) AIProcessUsage() llm.Usage
- func (s *Service) AIPurgeExcessSessions() int64
- func (s *Service) AIResetSession(user, sessionID string) error
- func (s *Service) AISessionUsage(user, sessionID string) (llm.Usage, bool)
- func (s *Service) AIStatus() AIStatus
- func (s *Service) AddConnection(ctx context.Context, rec ConnRecord) (ConnRecord, error)
- func (s *Service) AddFavorite(user string, f *SQLFavorite) error
- func (s *Service) BrowseDirs(ctx context.Context, path string) (DirBrowseResult, error)
- func (s *Service) CancelTask(taskID string) error
- func (s *Service) ClearSQLHistory(user, connID string)
- func (s *Service) Close() error
- func (s *Service) Config() *AppConfig
- func (s *Service) CreateSnapshot(ctx context.Context, connID string, dbNames []string, name, description string, ...) (*Snapshot, error)
- func (s *Service) DeleteConnection(key string) error
- func (s *Service) DeleteFavorite(user, id string) error
- func (s *Service) DeleteHistory(taskID string) error
- func (s *Service) DeleteSnapshot(id string) error
- func (s *Service) DeleteTableRows(ctx context.Context, connKey, dbName, table string, pkColumns []string, ...) (int64, error)
- func (s *Service) DeleteTask(id string) error
- func (s *Service) DeleteWorkspace(user, connID string) error
- func (s *Service) ExportTableExcel(ctx context.Context, connKey, dbName, table string, ...) ([]byte, int64, bool, error)
- func (s *Service) GenerateSQL(ctx context.Context, connKey, dbName string, p engine.GenSQLParams) (string, error)
- func (s *Service) GetCellValue(ctx context.Context, connKey, dbName, table, column string, pkColumns []string, ...) (any, error)
- func (s *Service) GetCompareResult(taskID string) (*CompareResult, error)
- func (s *Service) GetConfigInfo() ConfigInfo
- func (s *Service) GetDatabaseList(ctx context.Context, connKey string, force bool) ([]string, error)
- func (s *Service) GetDbObjects(ctx context.Context, connKey, dbName string, force bool) (*engine.DBTables, error)
- func (s *Service) GetDbSchemas(ctx context.Context, connKey, dbName string, force bool) ([]engine.SchemaSummary, error)
- func (s *Service) GetHistory(taskID string) (ExecutionRecord, error)
- func (s *Service) GetLastTask(taskType string) *TaskConfig
- func (s *Service) GetObjectDDL(ctx context.Context, connKey, dbName, objType, name string) (*ObjectDDLResult, error)
- func (s *Service) GetSchemaObjects(ctx context.Context, connKey, dbName, schema string, force bool) (*engine.DBSchema, error)
- func (s *Service) GetSnapshot(id string) (*Snapshot, error)
- func (s *Service) GetSnapshotCompareResult(taskID string) (*CompareResult, error)
- func (s *Service) GetTableColumns(ctx context.Context, connKey, dbName, tableName string) ([]engine.TableColumnInfo, error)
- func (s *Service) GetTableTree(ctx context.Context, connKey, dbName string) ([]engine.DBTables, error)
- func (s *Service) GetTask(id string) (TaskConfig, error)
- func (s *Service) InsertTableRow(ctx context.Context, connKey, dbName string, p engine.InsertRowParams) (int64, error)
- func (s *Service) ListConnections() []ConnInfo
- func (s *Service) ListFavorites(user string) []*SQLFavorite
- func (s *Service) ListHistory(taskType, taskConfigID string) []ExecutionRecord
- func (s *Service) ListSnapshots(connID string) []SnapshotInfo
- func (s *Service) ListTasks(taskType string) []TaskConfig
- func (s *Service) LoadWorkspace(user, connID string) (WorkspaceState, bool)
- func (s *Service) LocalArtifactPath(p string) (string, error)
- func (s *Service) OpenArtifact(logical string) (io.ReadCloser, int64, error)
- func (s *Service) Persist() *PersistMgr
- func (s *Service) PingConnection(ctx context.Context, connKey string) (int64, error)
- func (s *Service) ProgressCh(taskID string) (<-chan ProgressInfo, func(), error)
- func (s *Service) QueryTablePage(ctx context.Context, connKey, dbName, table string, page, pageSize int, ...) (*engine.TablePageResult, error)
- func (s *Service) RenameFavorite(user, id, title string) error
- func (s *Service) RunCompare(ctx context.Context, opts CompareOptions, cb ProgressFunc) (*CompareResult, error)
- func (s *Service) RunCompareRecorded(ctx context.Context, opts CompareOptions, cb ProgressFunc, taskConfigID string) (string, *CompareResult, error)
- func (s *Service) RunDictionary(ctx context.Context, opts DictionaryOptions, cb ProgressFunc) (string, error)
- func (s *Service) RunExport(ctx context.Context, opts ExportOptions, cb ProgressFunc) (string, error)
- func (s *Service) RunImport(ctx context.Context, opts ImportOptions, cb ProgressFunc) (*engine.ImportResult, error)
- func (s *Service) RunMigrate(ctx context.Context, opts MigrateOptions, cb ProgressFunc) error
- func (s *Service) RunSQLScript(ctx context.Context, connKey, dbName, sql string, limit, offset int, ...) ([]*engine.SQLQueryResult, error)
- func (s *Service) RunSnapshotCompareRecorded(ctx context.Context, snap *Snapshot, target *DBConnInfo, ...) (string, *CompareResult, error)
- func (s *Service) RunTaskByID(taskID string) (string, error)
- func (s *Service) SQLAudit(user, connID string, limit, offset int) ([]SQLAuditEntry, error)
- func (s *Service) SQLHistory(user, connID string) []SQLHistoryItem
- func (s *Service) SaveConfig(ctx context.Context, cfg AppConfig) error
- func (s *Service) SaveTask(task *TaskConfig) error
- func (s *Service) SaveWorkspace(user, connID string, state WorkspaceState) error
- func (s *Service) StartCompare(opts CompareOptions, taskConfigID string) (string, error)
- func (s *Service) StartDictionary(opts DictionaryOptions, taskConfigID string) (string, error)
- func (s *Service) StartExport(opts ExportOptions, taskConfigID string) (string, error)
- func (s *Service) StartImport(opts ImportOptions, taskConfigID string) (string, error)
- func (s *Service) StartMigrate(opts MigrateOptions, taskConfigID string) (string, error)
- func (s *Service) StartSnapshotCompare(opts SnapshotCompareOptions, taskConfigID string) (string, error)
- func (s *Service) StoreMode() StoreMode
- func (s *Service) TestConnection(ctx context.Context, conn DBConnInfo) error
- func (s *Service) UpdateTableCell(ctx context.Context, connKey, dbName string, p engine.UpdateCellParams) (int64, error)
- type Snapshot
- type SnapshotCompareOptions
- type SnapshotInfo
- type SnapshotTable
- type StoreMode
- type SvcError
- type TabSettings
- type TableAlias
- type TableCondition
- type TaskConfig
- type TaskHooks
- type TaskRunner
- type TaskStartInfo
- type WebAccessInfo
- type WebConfig
- type WorkspaceState
- type WorkspaceTab
Constants ¶
const ( ErrUnsupportedType = 2002 // 不支持的数据库类型 ErrConnNotFound = 2001 // 连接配置不存在 ErrConnNotSpecified = 2008 // 未指定数据库连接 ErrConnFailed = 2009 // 数据库连接/操作失败 ErrTaskNotFound = 2003 // 任务不存在 ErrTaskInvalid = 2010 // 任务配置无效(缺少选项/未知类型) ErrExecFailed = 2004 // 执行操作失败(导出/导入/迁移/获取表等) ErrFileType = 2005 // 不支持的文件类型 ErrNoArtifact = 2006 // 任务没有可下载产物 ErrOpenDirFailed = 2007 // 打开目录失败 ErrCryptoFailed = 2011 // 配置文件加解密失败 ErrHistoryRunning = 2012 // 任务运行中,无法删除历史记录 ErrTokenExpired = 2013 // Web 访问令牌过期 ErrAuthFailed = 2014 // 认证失败(缺少令牌或令牌无效) ErrRateLimited = 2015 // 认证失败过于频繁被临时锁定 ErrAccessDenied = 2016 // 访问来源不在白名单 ErrStreamUnsupported = 2017 // 环境不支持流式输出 ErrServiceException = 2018 // 服务异常 ErrAITimeout = 2019 // AI 生成超时 ErrAINotConfigured = 2020 // AI 功能未配置 ErrAISessionNotFound = 2021 // AI 会话不存在或已过期 ErrAIEmptyPrompt = 2022 // AI 需求描述为空 ErrAINoTargetDB = 2023 // 未找到可用数据库 ErrAINoTables = 2024 // 目标库没有可用的表 ErrAISchemaFailed = 2025 // 获取表结构失败 ErrAIEmptyResponse = 2026 // 模型未返回有效结果(空结果或仅思考过程) ErrExpOutDir = 2027 // 库模式(StoreNone 且无 DataDir)下未显式指定产物输出目录 ErrClientClosed = 2028 // 客户端已关闭(Close 后调用能力方法) ErrNotImplemented = 2029 // 触发式能力尚未实现(WithStoreConn/WithCacheRedis/WithArtifactStore 等) ErrCtbUnknown = 2031 // 业务对象贡献者未注册(任务引用的 Type 无导出/导入回调) )
业务错误码(cygin 系统码 1001~1012 之外,本项目从 2001 起)
const ( ResetNone = store.ResetNone ResetTruncate = store.ResetTruncate ResetDrop = store.ResetDrop // FormatSQL / FormatJSON 导出产物格式(ExportOptions.Format) FormatSQL = store.FormatSQL FormatJSON = store.FormatJSON )
重置模式常量
const ( UploadDirName = "uploads" TempDirName = "tmp" ExportDirName = "exports" CompareDirName = "compares" SnapshotDirName = "snapshots" )
数据根目录(默认 ~/.dqex,--data-dir 可覆盖)下的子目录规划:
- 根目录:SQLite 数据库(dqex.db)
- uploads:Web 上传文件临时目录
- tmp:任务处理临时目录(如 zip 解压,任务结束自动清理)
- exports:导出产物目录(导出 zip/目录)
- compares:对比报告目录(compare-<ID>.json)
- snapshots:快照目录(index.json + <snapshot-id>.json)
const ( // LocalUser 独立部署(无宿主身份头)时的默认用户域。 LocalUser = "local" // MaxUserLen 用户标识长度上限(超出截断,防列溢出)。 MaxUserLen = 64 )
const DefaultConfigName = "config.yaml"
DefaultConfigName 全局配置文件默认名(位于默认数据目录 ~/.dqex/ 下)
const EnvConfigFile = "dqex_CONFIG"
EnvConfigFile 指定全局配置文件的环境变量
Variables ¶
var ErrAISessionMissing = errors.New("ai session not found")
ErrAISessionMissing 指定 AI 会话不存在或不属于该用户域。 注:errors.go 中的 ErrAISessionNotFound 为 Web 层错误码(int 常量), 此处为持久层哨兵错误,命名避开冲突。
var ErrStoreDisabled = errors.New("store disabled: library mode without data dir")
ErrStoreDisabled 表示当前为 StoreNone 库模式(未配置数据目录),持久化能力不可用。
var SupportedDBTypes = store.SupportedDBTypes
SupportedDBTypes 支持的数据库类型及子类型。 SubType 不代表版本号,而是标识“使用该类型兼容模式的具体数据库产品”(彼此存在语法差异): 首项为原生标准库(值等于类型名),其余为兼容库产品。
Functions ¶
func FindConfigFile ¶
FindConfigFile 确定全局配置文件路径:显式指定 > 环境变量 dqex_CONFIG > ~/.dqex/config.yaml(缺省位置不存在时返回 "")
func IsArtifactLogicalPath ¶
IsArtifactLogicalPath 判定 OutputPath 是否为逻辑路径(<prefix>/<name>),供 Web 层分流
func NormalizeUser ¶
NormalizeUser 规范化用户标识:去空白、限长、剔除作用域分隔符;空回退 local。
func SaveAIProviders ¶
func SaveAIProviders(providers []AIProviderItem) error
SaveAIProviders 保存自定义厂商配置到本地 YAML 文件。 内置厂商的修改也会被保存(加载时覆盖内置默认值)。
func SetProvidersDataDir ¶
func SetProvidersDataDir(dir string)
SetProvidersDataDir 设置数据目录(在 Service 初始化时调用),用于加载本地厂商配置。
Types ¶
type AIConfig ¶
type AIConfig struct {
BaseURL string `yaml:"base_url" json:"baseUrl"` // OpenAI 兼容端点,如 https://api.openai.com/v1 或国内中转
APIKey string `yaml:"api_key,omitempty" json:"apiKey"` // API Key(保存后不回显明文)
Model string `yaml:"model" json:"model"` // 模型名,如 gpt-4o-mini / deepseek-chat
Temperature float32 `yaml:"temperature,omitempty" json:"temperature"` // 温度 0-2,默认 0.2
MaxTokens int `yaml:"max_tokens,omitempty" json:"maxTokens"` // 单次回复最大 token,默认 2048
TimeoutSec int `yaml:"timeout_sec,omitempty" json:"timeoutSec"` // 请求超时(秒),默认 60
MaxSchemaChars int `yaml:"max_schema_chars,omitempty" json:"maxSchemaChars"` // AI 可参考的表结构文本字符上限,默认 20000
SystemPrompt string `yaml:"system_prompt,omitempty" json:"systemPrompt"` // 自定义 system prompt 模板(支持 {dialect}/{schema} 占位符),留空用内置默认
}
AIConfig AI 辅助 SQL 配置(OpenAI 兼容协议,可对接 OpenAI / 国产模型等)。 前端编辑后通过 SaveConfig 保存;APIKey 保存后以掩码形式回显。
type AIModelInfo ¶
type AIModelInfo struct {
Name string `json:"name"`
Context int `json:"context"` // 上下文窗口大小(K tokens)
MaxTokens int `json:"maxTokens"` // 单次回复最大 token(0 表示未设置)
}
AIModelInfo 模型信息(名称 + 上下文窗口 + 单次回复上限)。
type AIProvider ¶
type AIProvider struct {
ID string `json:"id"`
Name string `json:"name"`
BaseURL string `json:"baseUrl"`
Models []AIModelInfo `json:"models"`
Builtin bool `json:"builtin,omitempty"` // 是否内置厂商(仅展示用)
}
AIProvider 厂商预设(API 响应结构,Models 含上下文信息)。
func AIProviders ¶
func AIProviders() []AIProvider
AIProviders 返回所有厂商列表(内置 + 本地配置合并,模型带上下文信息,标记 builtin)。
type AIProviderConfig ¶
type AIProviderConfig struct {
Providers []AIProviderStored `yaml:"providers"`
}
AIProviderConfig 本地配置文件结构(~/.dqex/ai_providers.yaml)。
type AIProviderItem ¶
type AIProviderItem struct {
ID string `json:"id"`
Name string `json:"name"`
BaseURL string `json:"baseUrl"`
Models []string `json:"models"`
}
AIProviderItem 前端管理接口使用的厂商结构(不含 Builtin 标记)。
type AIProviderStored ¶
type AIProviderStored struct {
ID string `yaml:"id"`
Name string `yaml:"name"`
BaseURL string `yaml:"base_url"`
Models []string `yaml:"models"`
}
AIProviderStored YAML 持久化结构(模型仅为名称列表,上下文由内置映射提供)。
type AISession ¶
type AISession struct {
ID string
Lang string // 会话语言(创建时 UI 语言,决定 prompt/回复语言;历史会话不回溯)
User string // 所属用户域(创建时从 ctx 注入;落盘 scope 与恢复校验用)
ConnKey string
TabID string // 所属 query tab(按 tab 隔离对话;空 = 不隔离,兼容旧调用)
DBName string
Dialect string
Messages []*schema.Message
Usage llm.Usage
Created time.Time
LastAt time.Time
// Agent 会话级 React Agent(独立 ChatModel 实例 + 只读工具,Reset 后复用)。
Agent *llm.ReactAgent
// Sys 名录 system prompt(Reset 重建用)。
Sys string
// ToolSink 工具调用事件出口(每次 aiChat 前设置,SSE 转发给前端)。
// 用 atomic.Value 存 func 类型:主 goroutine 写、工具 goroutine 读,避免 data race。
ToolSink atomic.Value // 存 func(name, args string)
// contains filtered or unexported fields
}
AISession 一次 AI 对话会话:绑定连接+库,累计 token,消息保留在内存。 采用「预注入表结构 + 工具兜底」模式:目标库的表结构(受 max_schema_tables/chars 限制) 预加载进 system prompt,模型无需自觉调工具即可用真实字段;超出预算的表仍可经 get_schema 按需查。
type AIStatus ¶
type AIStatus struct {
Enabled bool `json:"enabled"` // 配置齐全(BaseURL / API Key / Model 三项非空)
BaseURL string `json:"baseUrl"` // 掩码后端点
Model string `json:"model"` // 模型名
Temperature float32 `json:"temperature"` // 温度
MaxTokens int `json:"maxTokens"` // 单次回复上限
TimeoutSec int `json:"timeoutSec"` // 请求超时(秒)
MaxSchemaChars int `json:"maxSchemaChars"` // 表结构文本字符上限
HasPrompt bool `json:"hasPrompt"` // 是否使用自定义 system prompt
}
AIStatus AI 能力状态视图。
type AppConfig ¶
type AppConfig struct {
Dirs DirConfig `yaml:"dirs" json:"dirs"`
Web WebConfig `yaml:"web" json:"web"`
AI AIConfig `yaml:"ai" json:"ai"`
CLI CLIConfig `yaml:"cli" json:"cli"`
// Debug 全局 debug 日志开关:开启后输出 debug 及以上级别日志(含 AI 链路)。
// 等效于命令行 --debug;修改后重启服务生效。
Debug bool `yaml:"debug,omitempty" json:"debug"`
// CompatCollation 全局默认:将 MySQL 8.0 特有排序规则(如 utf8mb4_0900_ai_ci)
// 替换为 MySQL 5.7 兼容的 utf8mb4_unicode_ci,使 DDL 可在低版本 MySQL 上执行。
// 可在单个迁移/导入任务中覆盖此全局默认值。
// 不带 omitempty:false 需显式持久化,避免重新加载后被默认值 true 覆盖。
CompatCollation bool `yaml:"compat_collation" json:"compatCollation"`
}
AppConfig 全局独立配置(config.yaml)
type CLIConfig ¶
type CLIConfig struct {
// DisplayMode 查询结果默认显示模式:auto=表格超宽自动降级(默认);table=强制表格;vertical=强制垂直
DisplayMode string `yaml:"display_mode,omitempty" json:"displayMode"`
}
CLIConfig CLI 交互终端配置(dqex sql)
type ConfigInfo ¶
type ConfigInfo struct {
// Config 当前生效的全局配置内容(可编辑项)
Config AppConfig `json:"config"`
// Resolved 解析后的六类最终目录(只读展示;除 data 根目录固定外,其余保存后立即热生效)
Resolved ResolvedDirs `json:"resolved"`
// ConfigFile 全局配置文件路径(空 = 未发现,保存时将写到默认位置 ~/.dqex/config.yaml)
ConfigFile string `json:"configFile"`
// DataDirOverride 是否由 --data-dir 启动参数覆盖了配置的 dirs.data(此时目录项修改不生效)
DataDirOverride bool `json:"dataDirOverride"`
}
ConfigInfo 全局配置的完整视图(配置内容 + 解析后目录 + 文件路径 + 派生标记)。
type ConnHooks ¶
type ConnHooks struct {
// OnResolved 连接解析成功后触发(source: inline/memory/provider/store)
OnResolved func(ctx context.Context, connKey string, source ConnSource)
// OnConnect 每次真实建连后触发(err=失败原因);宿主日志场景注意遮蔽 Pwd 字段
OnConnect func(ctx context.Context, conn *DBConnInfo, err error)
// OnAdded AddConnection 成功后触发(任意模式,内存/落盘均触发)
OnAdded func(rec ConnRecord)
// OnDeleted DeleteConnection 成功后触发(任意模式)
OnDeleted func(key string)
}
ConnHooks 连接生命周期回调(审计/监控用,宿主可选注册)。 契约:回调运行在 dqex 的调用 goroutine 上,OnConnect 在关键路径上必须快速返回; 回调内不得再回调 dqex 的 Client 方法;参数中的连接结构由 dqex 持有副本,回调方不得复用修改。
type ConnProvider ¶
type ConnProvider struct {
// ListConns 返回外部连接列表(供 ListConnections / 元数据遍历使用)。
// 返回的密码字段宿主自行决定是否填充(List 场景可脱敏)。
ListConns func(ctx context.Context) ([]ConnInfo, error)
// GetConn 按 connKey 取一个连接用于实际建连,密码必须是可用的明文。
// 返回 (nil, nil) 表示不认识该 key(dqex 继续尝试后续来源,最终返回 ErrConnNotFound)。
GetConn func(ctx context.Context, connKey string) (*DBConnInfo, error)
}
ConnProvider 连接提供者回调:连接列表完全由外部持有,库内部不维护连接。 两个回调都可能被并发调用,实现方必须线程安全。
type ConnSource ¶
type ConnSource string
ConnSource 连接解析来源(ConnHooks.OnResolved 参数)
const ( ConnSourceInline ConnSource = "inline" // 任务参数直接携带的连接 ConnSourceMemory ConnSource = "memory" // 内存注册表(WithInlineConns / StoreNone 下 AddConnection) ConnSourceProvider ConnSource = "provider" // ConnProvider.GetConn 动态外部源 ConnSourceStore ConnSource = "store" // 持久化存储(仅 StoreSQLite) )
type ContributorImportRequest ¶
type ContributorImportRequest = store.ContributorImportRequest
ContributorImportRequest 贡献者导入回调请求
type ContributorRequest ¶
type ContributorRequest = store.ContributorRequest
ContributorRequest 贡献者导出回调请求
type ContributorResult ¶
type ContributorResult = store.ContributorResult
ContributorResult 贡献者导出回调结果
type CreateSnapshotOptions ¶
type CreateSnapshotOptions = store.CreateSnapshotOptions
CreateSnapshotOptions 创建快照选项
type DataPrepareRequest ¶
type DataPrepareRequest = store.DataPrepareRequest
DataPrepareRequest 数据前置处理请求
type DictionaryOptions ¶
type DictionaryOptions = store.DictionaryOptions
DictionaryOptions 数据字典导出选项
type DirBrowseResult ¶
type DirBrowseResult struct {
Path string `json:"path"` // 当前浏览路径
Parent string `json:"parent"` // 上级目录路径(已到浏览范围边界时为空)
Root string `json:"root"` // 浏览范围根目录(用户主目录,不可超出)
Entries []DirEntry `json:"entries"` // 子目录列表(目录在前,隐藏目录排后)
}
DirBrowseResult 目录浏览结果(仅目录,不含文件)
type DirConfig ¶
type DirConfig struct {
Data string `yaml:"data" json:"data"` // ① 配置保存目录(connections/tasks/history)
Tmp string `yaml:"tmp" json:"tmp"` // ② 任务处理临时目录
Uploads string `yaml:"uploads" json:"uploads"` // ③ Web 上传临时目录
Exports string `yaml:"exports" json:"exports"` // ④ 导出产物目录
Compares string `yaml:"compares" json:"compares"` // ⑤ 对比报告目录
Snapshots string `yaml:"snapshots" json:"snapshots"` // ⑥ 快照目录
}
DirConfig 六类数据目录配置(留空 = 由 data 目录派生)
type LibraryOptions ¶
type LibraryOptions struct {
// DataDir 持久化根目录:非空 = StoreSQLite(快照/历史/连接库落盘);空 = StoreNone 纯内存
DataDir string
// StoreConn 外部 SQL 存储连接(StoreExternal):非空时元数据(连接/任务/历史/审计/
// 工作区/AI 会话)经 cydb 落入宿主数据库(独立 database,表自动迁移),
// 不写本地 SQLite;DataDir 仅决定目录类资源(tmp/uploads/exports/compares/snapshots)
// 的本地位置,为空时回退系统临时目录。优先级高于 DataDir。
StoreConn *cydbdef.DBConnection
// ConfigFile 显式全局配置路径;空 = 不加载全局配置(不自动发现 ~/.dqex/config.yaml)
ConfigFile string
// AI AI 辅助 SQL 配置注入(宿主持有,dqex 不落盘):BaseURL/APIKey/Model 三项
// 非空即启用 AI 助手;非 nil 时覆盖 ConfigFile 中的 ai 段,nil 时不影响
AI *AIConfig
// InlineConns 静态注入的连接(便捷糖:内部转成只读内存注册表)
InlineConns []ConnInfo
// Provider 连接提供者回调(连接完全外部持有时注入)
Provider *ConnProvider
// Hooks 连接生命周期回调(可选)
Hooks *ConnHooks
// Contributors 业务对象贡献者模板(代理层):任务按 Type 引用,回调由此处补齐
Contributors []Contributor
// QueryHooks SQL 审计钩子:任务/查询执行逐语句回调(OnQuery),宿主接合规审计
QueryHooks *engine.QueryHooks
// DataPreparers 数据前置处理器(代理层,key=目标库名):.json 数据包导入前回调宿主
// 做版本合并等业务策略,可修改包内容
DataPreparers map[string]engine.DataPreparer
// TaskHooks 任务生命周期回调(可选):Web 异步任务启动/进度推送时回调宿主,
// 用于任务镜像/通知;nil 时零开销,CLI/Web 独立形态不注入
TaskHooks *TaskHooks
// ArtifactStore 快照对象存储(可选):非空时快照(index + 数据)落对象存储
// (key 前缀 snapshots/),解决容器化部署本地盘易失;nil 时落本地目录(默认行为)
ArtifactStore *cystore.Store
// ArtifactBucket 对象存储 bucket(空 = store 默认 bucket)
ArtifactBucket string
}
LibraryOptions 库模式构建参数(门面包使用;CLI/Web 不经此路径)
type ObjectDDLResult ¶
type ObjectDDLResult struct {
Type string `json:"type"` // table / view / function / procedure
Name string `json:"name"`
DDL string `json:"ddl"`
}
ObjectDDLResult 对象创建语句查询结果
type PersistMgr ¶
type PersistMgr struct {
// contains filtered or unexported fields
}
PersistMgr 统一持久化管理:连接配置 + 任务配置 + 执行历史 + SQL 历史 + SQL 审计 + Web 凭证, 全部存储于 SQLite(dqex.db),目录类资源(上传/临时/导出/对比/快照)仍为文件系统目录。
func NewPersistMgr ¶
func NewPersistMgr(baseDir string) (*PersistMgr, error)
NewPersistMgr 创建持久化管理器(默认 ~/.dqex/,子目录由 data 目录派生)
func NewPersistMgrWith ¶
func NewPersistMgrWith(dirs ResolvedDirs) (*PersistMgr, error)
NewPersistMgrWith 按解析后的五类目录创建持久化管理器,并打开 SQLite 存储。
func NewPersistMgrWithStore ¶
func NewPersistMgrWithStore(dirs ResolvedDirs, st store.Store) (*PersistMgr, error)
NewPersistMgrWithStore 按解析后的五类目录创建持久化管理器,注入外部 SQL 存储 (StoreExternal 库模式:宿主经 WithStoreConn 注入 MySQL 等连接,元数据不落本地文件)。 目录类资源(tmp/uploads/exports/compares/snapshots)仍为本地目录。
func (*PersistMgr) AISessionExists ¶
func (p *PersistMgr) AISessionExists(sessionID string) bool
AISessionExists 判断会话 ID 是否已落盘(跨用户域存在性判定,不含归属校验)。 供透明重建复用原 ID 前区分「彻底不存在」与「存在但归属其他用户域」。
func (*PersistMgr) AddFavorite ¶
func (p *PersistMgr) AddFavorite(user string, f *SQLFavorite) error
AddFavorite 新增一条收藏(user 为所属用户域)
func (*PersistMgr) AddSQLHistory ¶
func (p *PersistMgr) AddSQLHistory(user string, item SQLHistoryItem) error
AddSQLHistory 追加一条 SQL 执行历史(每连接环形保留最近 N 条)。 item.ConnID 为裸连接 key(原始宿主连接标识);user 为所属用户域(store 层统一 计算作用域键并三列同写:user/conn_key/conn_id)。
func (*PersistMgr) AppendSQLAudit ¶
func (p *PersistMgr) AppendSQLAudit(user string, entry SQLAuditEntry) error
AppendSQLAudit 追加一条 SQL 审计日志(只追加,不提供删除)。 entry.ConnID 为裸连接 key(原始宿主连接标识);user 为所属用户域(store 层统一 计算作用域键并三列同写)。
func (*PersistMgr) ClearSQLHistory ¶
func (p *PersistMgr) ClearSQLHistory(user, connID string) error
ClearSQLHistory 清空某用户域下某连接的历史
func (*PersistMgr) CompareDir ¶
func (p *PersistMgr) CompareDir() string
CompareDir 返回对比报告目录(compare-<ID>.json)
func (*PersistMgr) DeleteAISession ¶
func (p *PersistMgr) DeleteAISession(user, sessionID string) error
DeleteAISession 删除指定会话(校验属于该用户域)。
func (*PersistMgr) DeleteAISessionByTab ¶
func (p *PersistMgr) DeleteAISessionByTab(user, connID, tabID string) error
DeleteAISessionByTab 删除某用户域下某连接指定 tab 的会话(tab 关闭时调用)。
func (*PersistMgr) DeleteAISessionsByConn ¶
func (p *PersistMgr) DeleteAISessionsByConn(user, connID string) error
DeleteAISessionsByConn 删除某用户域下某连接的全部会话。
func (*PersistMgr) DeleteAllUsersAISessionsByConn ¶
func (p *PersistMgr) DeleteAllUsersAISessionsByConn(connID string) error
DeleteAllUsersAISessionsByConn 跨用户域删除某连接的全部 AI 会话(连接删除级联清理)。 connID 为裸连接 key,store 层按 conn_key 列等值一次删除所有用户域的会话。
func (*PersistMgr) DeleteAllUsersWorkspacesByConn ¶
func (p *PersistMgr) DeleteAllUsersWorkspacesByConn(connID string) error
DeleteAllUsersWorkspacesByConn 跨用户域删除某连接的全部工作区(连接删除级联清理)。 connID 为裸连接 key,store 层按 conn_key 列等值一次删除所有用户域的行。
func (*PersistMgr) DeleteConn ¶
func (p *PersistMgr) DeleteConn(key string) error
DeleteConn 删除连接配置(按主键 ID,兼容名称或短名)
func (*PersistMgr) DeleteFavorite ¶
func (p *PersistMgr) DeleteFavorite(user, id string) error
DeleteFavorite 删除收藏(按 id 定位,仅限本用户域)
func (*PersistMgr) DeleteHistory ¶
func (p *PersistMgr) DeleteHistory(id string) error
DeleteHistory 删除指定执行记录
func (*PersistMgr) DeleteSnapshot ¶
func (p *PersistMgr) DeleteSnapshot(id string) error
DeleteSnapshot 删除快照索引行(按 ID)
func (*PersistMgr) DeleteTask ¶
func (p *PersistMgr) DeleteTask(taskID string) error
DeleteTask 删除任务配置
func (*PersistMgr) DeleteWorkspace ¶
func (p *PersistMgr) DeleteWorkspace(user, connID string) error
DeleteWorkspace 删除某用户域下某连接的工作区。connID 为裸连接 key。
func (*PersistMgr) ExportDir ¶
func (p *PersistMgr) ExportDir() string
ExportDir 返回导出产物目录(导出 zip/目录)
func (*PersistMgr) GetConn ¶
func (p *PersistMgr) GetConn(key string) (ConnRecord, bool)
GetConn 按主键 ID 查找连接;兼容按名称或短名查找(旧任务配置引用)
func (*PersistMgr) GetHistory ¶
func (p *PersistMgr) GetHistory(id string) (ExecutionRecord, error)
GetHistory 获取指定执行记录
func (*PersistMgr) GetLastUsed ¶
func (p *PersistMgr) GetLastUsed(taskType string) *TaskConfig
GetLastUsed 获取指定类型最近使用的任务配置
func (*PersistMgr) GetMeta ¶
func (p *PersistMgr) GetMeta(key string) (string, bool, error)
GetMeta 读取 KV 元信息;无记录时 ok=false
func (*PersistMgr) GetTask ¶
func (p *PersistMgr) GetTask(id string) (TaskConfig, bool)
GetTask 获取指定任务配置
func (*PersistMgr) ListAISessions ¶
func (p *PersistMgr) ListAISessions(user, connID, tabID string) []AISessionRecord
ListAISessions 列出某用户域下某连接(可选指定 tab)的会话(新→旧,仅元信息不含消息)。 connID 为裸连接 key,跨用户隔离由 store 层 user 列保证。
func (*PersistMgr) ListFavorites ¶
func (p *PersistMgr) ListFavorites(user string) []*SQLFavorite
ListFavorites 返回该用户域的全部收藏(新→旧)
func (*PersistMgr) ListSQLAudit ¶
func (p *PersistMgr) ListSQLAudit(user, connID string, limit, offset int) ([]SQLAuditEntry, error)
ListSQLAudit 读取审计日志(倒序,分页)。connID 为裸连接 key,为空时返回该用户域 全部连接:store 层仅按 user 列过滤,跨用户隔离由 user 列保证(独立部署 local 域同理)。
func (*PersistMgr) ListSQLHistory ¶
func (p *PersistMgr) ListSQLHistory(user, connID string) []SQLHistoryItem
ListSQLHistory 返回某用户域下某连接的历史(新→旧)。connID 为裸连接 key, 为空时返回该用户域全部连接。
func (*PersistMgr) ListSnapshots ¶
func (p *PersistMgr) ListSnapshots(connID string) ([]SnapshotInfo, error)
ListSnapshots 列出快照索引(created_at 倒序)。connID 非空时按 conn_id 过滤。 存储不可用(StoreNone)时返回 ErrStoreDisabled,由调用方回退 JSON 索引路径。
func (*PersistMgr) LoadAISession ¶
func (p *PersistMgr) LoadAISession(user, sessionID string) (AISessionRecord, bool)
LoadAISession 读取指定会话(store 层按 user 列做归属校验,不属于该用户域时 ok=false)。 rec.ConnID 已还原为裸连接 key,无需再做作用域还原。
func (*PersistMgr) LoadConns ¶
func (p *PersistMgr) LoadConns() map[string]ConnRecord
LoadConns 加载全部连接配置(按 ID 索引)
func (*PersistMgr) LoadHistory ¶
func (p *PersistMgr) LoadHistory(taskType, taskConfigID string) []ExecutionRecord
LoadHistory 加载执行历史(taskType 为空=全部,taskConfigID 为空=不过滤)
func (*PersistMgr) LoadWebAccess ¶
func (p *PersistMgr) LoadWebAccess() (WebAccessInfo, bool)
LoadWebAccess 读取 Web 访问凭证;文件不存在或无有效内容时 ok=false
func (*PersistMgr) LoadWorkspace ¶
func (p *PersistMgr) LoadWorkspace(user, connID string) (WorkspaceState, bool)
LoadWorkspace 读取某用户域下某连接的工作区;无记录时 ok=false。connID 为裸连接 key。
func (*PersistMgr) MarkLastUsed ¶
func (p *PersistMgr) MarkLastUsed(taskID, taskType string) error
MarkLastUsed 标记指定类型为最近使用(同类型其他任务取消标记)
func (*PersistMgr) PurgeExcessAISessions ¶
func (p *PersistMgr) PurgeExcessAISessions(maxPerConn, keepDays int) (int64, error)
PurgeExcessAISessions 清理超额会话(会话数 > maxPerConn 且超过 keepDays 天未活动),返回删除条数。
func (*PersistMgr) RemoveArtifact ¶
func (p *PersistMgr) RemoveArtifact(outputPath string)
RemoveArtifact 清理执行记录 OutputPath 指向的产物文件(目录或文件均可)。 安全边界:仅清理 exports/compares 受管目录内的产物,用户自定义输出路径 (export -o / compare --output)不动;文件不存在时静默跳过。
func (*PersistMgr) RenameFavorite ¶
func (p *PersistMgr) RenameFavorite(user, id, title string) error
RenameFavorite 重命名收藏(按 id 定位,仅限本用户域)
func (*PersistMgr) SaveAISession ¶
func (p *PersistMgr) SaveAISession(user string, rec AISessionRecord) error
SaveAISession 保存/更新一个 AI 会话(整组消息覆盖写;rec.ConnID 为裸连接 key, user 为所属用户域,store 层统一计算作用域键并三列同写)。
func (*PersistMgr) SaveConn ¶
func (p *PersistMgr) SaveConn(rec ConnRecord) (ConnRecord, error)
SaveConn 保存连接配置:rec.ID 非空则按主键更新,否则生成新 xid
func (*PersistMgr) SaveHistory ¶
func (p *PersistMgr) SaveHistory(record ExecutionRecord) error
SaveHistory 保存执行历史(按 ID 更新或新增,超出上限裁剪最旧记录)
func (*PersistMgr) SaveTask ¶
func (p *PersistMgr) SaveTask(task TaskConfig) error
SaveTask 保存任务配置(按 ID 更新或新增)
func (*PersistMgr) SaveWebAccess ¶
func (p *PersistMgr) SaveWebAccess(info WebAccessInfo) error
SaveWebAccess 保存 Web 访问凭证(0600 落盘)
func (*PersistMgr) SaveWorkspace ¶
func (p *PersistMgr) SaveWorkspace(user, connID string, state WorkspaceState) error
SaveWorkspace 保存某用户域下某连接的工作区(整体覆盖)。connID 为裸连接 key。
func (*PersistMgr) SetMeta ¶
func (p *PersistMgr) SetMeta(key, value string) error
SetMeta 写入/更新 KV 元信息(按 key 幂等)
func (*PersistMgr) SetSnapshotsExternal ¶
func (p *PersistMgr) SetSnapshotsExternal(v bool)
SetSnapshotsExternal 标记快照持久化已切换对象存储(WithArtifactStore): UpdateDirs 热更新时跳过 snapshots 目录迁移(对象 key 不受本地目录变更影响)。
func (*PersistMgr) TempDir ¶
func (p *PersistMgr) TempDir() string
TempDir 返回任务处理临时目录(zip 解压等,任务结束自动清理)
func (*PersistMgr) UpdateDirs ¶
func (p *PersistMgr) UpdateDirs(dirs ResolvedDirs) error
UpdateDirs 运行时热更新子目录(不修改 baseDir,因 SQLite 已打开)。 产物类目录(exports/compares/snapshots)变更时自动迁移原数据到新目录,并同步 重写执行历史中的产物路径(OutputPath 保持全路径),保证历史下载始终可用; tmp/uploads 为临时目录(任务结束自动清理),不做迁移。
func (*PersistMgr) UpsertSnapshot ¶
func (p *PersistMgr) UpsertSnapshot(info SnapshotInfo) error
UpsertSnapshot 写入/更新快照索引行(按 info.ID 幂等)
type ResolvedDirs ¶
type ResolvedDirs struct {
Data string `json:"data"`
Tmp string `json:"tmp"`
Uploads string `json:"uploads"`
Exports string `json:"exports"`
Compares string `json:"compares"`
Snapshots string `json:"snapshots"`
}
ResolvedDirs 解析后的最终目录
func ResolveDirs ¶
func ResolveDirs(dataDirFlag string, cfg *AppConfig) ResolvedDirs
ResolveDirs 计算最终目录。优先级:--data-dir flag > 配置文件 dirs.data > 默认 ~/.dqex; 其余目录:配置文件显式值 > 由 data 目录派生
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service 业务服务层:Web/CLI 共用,编排引擎 + 连接 + 任务 + 历史 + AI 辅助
func NewLibraryService ¶
func NewLibraryService(ctx context.Context, opts LibraryOptions) (*Service, error)
NewLibraryService 创建库模式业务服务: DataDir 非空走 StoreSQLite(与 NewServiceWith 等价的持久化链路), DataDir 为空走 StoreNone(无 SQLite、无配置发现,连接仅内存/回调提供)。
func NewService ¶
NewService 创建业务服务(自动发现全局配置 config.yaml)
func NewServiceWith ¶
NewServiceWith 创建业务服务:configFile 显式指定全局配置,空则按默认顺序发现; ctx 携带请求语言(cli 注入 WithLang),配置加载错误的 details 按语言渲染。
func (*Service) AIChat ¶
func (s *Service) AIChat(ctx context.Context, sessionID, action, task, msgID string) (string, llm.Usage, bool, error)
AIChat 非流式对话:追加用户消息 → 生成 → 追加助手消息 → 返回文本 + 本轮 usage。 action 取值 generate/explain/fix/optimize,空视为 generate;task 为需求文本或原始 SQL。 schemaVerified 表示本轮是否调用过 get_schema(真实表结构已验证),供前端可靠度标记。
func (*Service) AIChatStream ¶
func (s *Service) AIChatStream(ctx context.Context, sessionID, action, task, msgID string, onDelta func(string), onTool func(string, string)) (llm.Usage, bool, error)
AIChatStream 流式对话:onDelta 每收到一段增量即回调,onTool 每次工具调用开始时回调(agent 模式)。 返回本轮累计 usage(模型未提供时记 0)+ 本轮是否已验证真实表结构(schemaVerified)。
func (*Service) AIChatStreamWithFallback ¶
func (s *Service) AIChatStreamWithFallback(ctx context.Context, lang, sessionID, action, task, msgID string, connID, db, tabID string, history []*schema.Message, onDelta func(string), onTool func(string, string)) (llm.Usage, bool, error)
AIChatStreamWithFallback 流式对话(Web 主链路):会话不存在时,用 connID/db/tabID/history 透明重建会话并继续(复用原 sessionID,前端无需感知会话生命周期、也无需更新 ID)。 lang 为请求语言(仅透明重建新会话时生效;从库恢复的会话沿用其原始语言)。 返回 usage + schemaVerified(本轮是否已验证真实表结构)。
func (*Service) AIDeleteSession ¶
AIDeleteSession 删除会话(校验归属:不存在或不属于当前用户均按会话不存在处理)。
func (*Service) AIDeleteSessionByTab ¶
AIDeleteSessionByTab 删除某连接下指定 tab 的会话(tab 关闭时调用),同步清理内存会话。
func (*Service) AIListSessions ¶
func (s *Service) AIListSessions(user, connID, tabID string) []AISessionRecord
AIListSessions 列出某用户域下某连接(可选指定 tab)的会话(新→旧,仅元信息,供前端恢复历史对话选择)。
func (*Service) AILoadSessionHistory ¶
func (s *Service) AILoadSessionHistory(user, sessionID string) []AISessionRecord
AILoadSessionHistory 读取某会话的对话历史(role/content 序列,供前端恢复展示)。 返回 nil 表示无记录。system 消息与空内容消息已过滤,仅返回 user/assistant 轮次。
func (*Service) AINewSession ¶
func (s *Service) AINewSession(ctx context.Context, lang, connKey, dbName, tabID string, history []*schema.Message, sessionID string) (*AISession, error)
AINewSession 创建 AI 会话(绑定连接+库+tab,注入轻量库/表名录)。返回会话句柄。 lang 为 UI 语言(决定 prompt 语言与模型回复语言)。 history 可选:会话重建时回放的历史对话(user/assistant 轮次)。 sessionID 可选:指定会话 ID(会话失效重建时复用原 ID,前端无需感知);传 "" 则自动生成。 tabID 可选:所属 query tab(按 tab 隔离对话;空 = 不隔离)。
func (*Service) AIProcessUsage ¶
AIProcessUsage 返回进程级累计 token(服务启动以来所有会话的总消耗)。
func (*Service) AIPurgeExcessSessions ¶
AIPurgeExcessSessions 清理超额会话: 仅当某连接会话数 > aiMaxSessionsPerConn 且某会话超过 aiSessionKeepDays 天未活动时清理; 否则(tab 未关闭)永久保留。在会话创建等时机调用,防止孤儿会话无限增长。
func (*Service) AIResetSession ¶
AIResetSession 清空会话消息(重建 system prompt)与累计 token。 内存会话不存在(空闲回收/进程重启)时回退清空落盘记录的消息并幂等成功: 否则前端重置只清了 UI,重进页面会从持久化恢复出旧对话。
func (*Service) AISessionUsage ¶
AISessionUsage 返回当前用户某会话的累计 token 消耗(他人会话按不存在处理)。
func (*Service) AddConnection ¶
func (s *Service) AddConnection(ctx context.Context, rec ConnRecord) (ConnRecord, error)
AddConnection 保存连接配置:rec.ID 非空为按主键更新,否则新建(生成 xid)。 StoreNone 库模式下不落盘、仅内存注册表生效(见 3.2/4.1);StoreSQLite 落盘持久化。
func (*Service) AddFavorite ¶
func (s *Service) AddFavorite(user string, f *SQLFavorite) error
AddFavorite 新增一条收藏。校验 SQL 非空、长度合理,标题缺省时取首行。
func (*Service) BrowseDirs ¶
BrowseDirs 列出 path 下的子目录,供设置页目录选择器使用。 浏览范围限制在用户主目录内:path 为空、不存在或超出范围时回退到主目录。
func (*Service) ClearSQLHistory ¶
ClearSQLHistory 清空某用户域下某连接的历史记录
func (*Service) CreateSnapshot ¶
func (s *Service) CreateSnapshot(ctx context.Context, connID string, dbNames []string, name, description string, includeSamples bool, sampleLimit int, lang string, cb ProgressFunc) (*Snapshot, error)
CreateSnapshot 创建快照(同步,CLI 使用)。dbNames 支持多库;空库名回退到连接默认库。 sampleLimit:每表采样行数上限;<=0 走引擎默认值。lang:进度日志语言(zh/en)。
func (*Service) DeleteConnection ¶
DeleteConnection 删除连接(按主键 ID,兼容名称/短名)。 StoreNone 库模式下仅删除内存注册表连接;StoreSQLite 落盘删除并级联清理。
func (*Service) DeleteFavorite ¶
DeleteFavorite 删除收藏(按 id 定位,仅限本用户域)
func (*Service) DeleteHistory ¶
DeleteHistory 删除执行记录并同步清理其产物文件(仅受管目录内);运行中的任务不允许删除
func (*Service) DeleteSnapshot ¶
DeleteSnapshot 删除快照(索引 + 数据文件/对象)。 persist 可用时先触发存量迁移(否则 CLI 直接删除存量快照会因 DB 未导入而误报不存在), 再删 DB 索引行;StoreNone 降级走 JSON 索引读-改-写。
func (*Service) DeleteTableRows ¶
func (s *Service) DeleteTableRows(ctx context.Context, connKey, dbName, table string, pkColumns []string, rows [][]any) (int64, error)
DeleteTableRows 删除表浏览中的整行(按主键定位,支持批量)。 逐行执行 DELETE(named bind + 标识符引用,防注入);返回累计影响行数。
func (*Service) DeleteWorkspace ¶
DeleteWorkspace 删除某用户域下某连接的工作区。
func (*Service) ExportTableExcel ¶
func (s *Service) ExportTableExcel(ctx context.Context, connKey, dbName, table string, sortSpecs []engine.SortSpec, filters []engine.ColumnFilter, maxRows int) ([]byte, int64, bool, error)
ExportTableExcel 表数据导出 Excel(应用过滤/排序),返回 xlsx 字节流 + 总行数 + 是否截断。 复用 engine.QueryTablePage 拿数据 + excelize 内存生成,不落盘。
func (*Service) GenerateSQL ¶
func (s *Service) GenerateSQL(ctx context.Context, connKey, dbName string, p engine.GenSQLParams) (string, error)
GenerateSQL 快速生成 SQL 文本(表浏览的行/单元格/过滤条件 → 方言正确的可执行语句)。 复用 engine 的 cydb 构建器(InlineLiterals 内联转义),生成仅产出文本不执行、不写审计。
func (*Service) GetCellValue ¶
func (s *Service) GetCellValue(ctx context.Context, connKey, dbName, table, column string, pkColumns []string, pkValues []any) (any, error)
GetCellValue 按主键 + 列名定位单行单列,返回该单元格的完整值(大字段懒加载)。 仅用于对象树表浏览场景;列名/主键列用标识符引用,值用命名参数绑定,防注入。
func (*Service) GetCompareResult ¶
func (s *Service) GetCompareResult(taskID string) (*CompareResult, error)
GetCompareResult 按 taskID 读取已落位的对比结果报告
func (*Service) GetConfigInfo ¶
func (s *Service) GetConfigInfo() ConfigInfo
GetConfigInfo 返回全局配置的完整视图(配置内容 + 解析目录 + 文件路径)。
func (*Service) GetDatabaseList ¶
func (s *Service) GetDatabaseList(ctx context.Context, connKey string, force bool) ([]string, error)
GetDatabaseList 获取指定连接的库名列表(分级加载第一层,不枚举对象); force=true 绕过缓存直查并覆盖回写(界面刷新),平时命中 10 分钟缓存加速展开。
func (*Service) GetDbObjects ¶
func (s *Service) GetDbObjects(ctx context.Context, connKey, dbName string, force bool) (*engine.DBTables, error)
GetDbObjects 获取指定库的对象清单(分级加载第二层,MySQL/Oracle 无 schema 层); force=true 绕过缓存直查并覆盖回写(界面刷新),平时命中 10 分钟缓存加速展开。
func (*Service) GetDbSchemas ¶
func (s *Service) GetDbSchemas(ctx context.Context, connKey, dbName string, force bool) ([]engine.SchemaSummary, error)
GetDbSchemas 获取指定库的 schema 列表(分级加载第二层,PG 系;非 PG 返回空); force=true 绕过缓存直查并覆盖回写(界面刷新),平时命中 10 分钟缓存加速展开。
func (*Service) GetHistory ¶
func (s *Service) GetHistory(taskID string) (ExecutionRecord, error)
GetHistory 获取执行记录
func (*Service) GetLastTask ¶
func (s *Service) GetLastTask(taskType string) *TaskConfig
GetLastTask 获取指定类型最近使用的任务配置
func (*Service) GetObjectDDL ¶
func (s *Service) GetObjectDDL(ctx context.Context, connKey, dbName, objType, name string) (*ObjectDDLResult, error)
GetObjectDDL 获取指定对象(表/视图/函数/存储过程)的创建语句。 dbName 覆盖连接默认库(Oracle 下即 schema);连接复用短生命周期、调用方无需关心。
func (*Service) GetSchemaObjects ¶
func (s *Service) GetSchemaObjects(ctx context.Context, connKey, dbName, schema string, force bool) (*engine.DBSchema, error)
GetSchemaObjects 获取指定库/schema 的对象清单(分级加载第三层,PG 系); force=true 绕过缓存直查并覆盖回写(界面刷新),平时命中 10 分钟缓存加速展开。
func (*Service) GetSnapshot ¶
GetSnapshot 获取单个快照完整数据
func (*Service) GetSnapshotCompareResult ¶
func (s *Service) GetSnapshotCompareResult(taskID string) (*CompareResult, error)
GetSnapshotCompareResult 读取快照对比结果
func (*Service) GetTableColumns ¶
func (s *Service) GetTableColumns(ctx context.Context, connKey, dbName, tableName string) ([]engine.TableColumnInfo, error)
GetTableColumns 获取指定连接/库下某表的列信息(名称/类型/可空/主键/默认值)
func (*Service) GetTableTree ¶
func (s *Service) GetTableTree(ctx context.Context, connKey, dbName string) ([]engine.DBTables, error)
GetTableTree 获取指定连接(可覆盖库名)的 库→表 树形结构; 连接未配置库时遍历所有库(Oracle 遍历 schema)
func (*Service) InsertTableRow ¶
func (s *Service) InsertTableRow(ctx context.Context, connKey, dbName string, p engine.InsertRowParams) (int64, error)
InsertTableRow 表浏览视图新增一行(INSERT,named bind + 标识符引用,防注入)。 columns/values 为用户显式填写的列(自增主键通常不传);返回影响行数。
func (*Service) ListConnections ¶
ListConnections 列出所有连接(按名称排序,保证前端展示稳定)。 来源合并:内存注册表 + 持久层(StoreSQLite)+ ConnProvider.ListConns(外部持有)。
func (*Service) ListFavorites ¶
func (s *Service) ListFavorites(user string) []*SQLFavorite
ListFavorites 返回该用户域的全部收藏(新→旧)
func (*Service) ListHistory ¶
func (s *Service) ListHistory(taskType, taskConfigID string) []ExecutionRecord
ListHistory 列出执行历史
func (*Service) ListSnapshots ¶
func (s *Service) ListSnapshots(connID string) []SnapshotInfo
ListSnapshots 列出快照摘要(始终返回非 nil 切片,避免 JSON 序列化为 null)。 persist 可用(StoreSQLite/StoreExternal)时走 DB 索引(connID 非空按 conn_id 列过滤); StoreNone 降级时回退 JSON 索引(OSS/本地),connID 在内存过滤。
func (*Service) ListTasks ¶
func (s *Service) ListTasks(taskType string) []TaskConfig
ListTasks 列出任务配置(taskType 为空=全部)
func (*Service) LoadWorkspace ¶
func (s *Service) LoadWorkspace(user, connID string) (WorkspaceState, bool)
LoadWorkspace 读取某用户域下某连接的工作区;无记录时返回空状态。
func (*Service) LocalArtifactPath ¶
LocalArtifactPath 将产物路径换算为本地文件系统路径:逻辑路径按受管目录展开 (对象存储模式无本地终态文件,返回错误);真实本地路径(目录产物/用户自定义输出)原样返回。
func (*Service) OpenArtifact ¶
OpenArtifact 打开产物读取流(Web 下载接口流式返回用),返回 reader 与大小(未知为 -1)。 仅接受逻辑路径;目录产物与用户自定义本地路径应由调用方走本地文件语义。
func (*Service) PingConnection ¶
PingConnection 检测连接可用性(SELECT 1),返回耗时(毫秒)。 库名为空的 PG 系连接依次尝试锚点候选库(postgres → template1),与对象树枚举逻辑一致, 避免 Kingbase/GaussDB 等兼容库因无 postgres 库误报连接失败。
func (*Service) ProgressCh ¶
func (s *Service) ProgressCh(taskID string) (<-chan ProgressInfo, func(), error)
ProgressCh 订阅任务进度(供 SSE 使用)
func (*Service) QueryTablePage ¶
func (s *Service) QueryTablePage(ctx context.Context, connKey, dbName, table string, page, pageSize int, sortSpecs []engine.SortSpec, excludeColumns []string, filters []engine.ColumnFilter) (*engine.TablePageResult, error)
QueryTablePage 对象树数据浏览:分页查询单表数据并一次返回全表总行数。 与 RunSQLQuery 不同:这是系统自动生成的浏览查询,不进「SQL 执行历史」、不写审计, 避免每次点开表都产生一条孤立的 SELECT COUNT(*) 审计记录(此前由前端二次 COUNT 造成)。 filters 为列过滤条件(AND 叠加),由 engine 层复用 cydb 条件构建器(值参数化绑定防注入)。
func (*Service) RenameFavorite ¶
RenameFavorite 重命名收藏(按 id 定位,仅限本用户域)
func (*Service) RunCompare ¶
func (s *Service) RunCompare(ctx context.Context, opts CompareOptions, cb ProgressFunc) (*CompareResult, error)
RunCompare 执行数据库对比(作用域为单个库对,两侧必须已选定库)
func (*Service) RunCompareRecorded ¶
func (s *Service) RunCompareRecorded(ctx context.Context, opts CompareOptions, cb ProgressFunc, taskConfigID string) (string, *CompareResult, error)
RunCompareRecorded 执行对比并记录历史:结果落盘 compares/compare-<ID>.json, 返回记录 ID,供 `compare show --id <ID>` 回看差异明细(CLI 同步执行路径用)
func (*Service) RunDictionary ¶
func (s *Service) RunDictionary(ctx context.Context, opts DictionaryOptions, cb ProgressFunc) (string, error)
RunDictionary 执行数据字典生成(同步,CLI 直接使用;Web 通过 StartDictionary 异步执行),返回产物路径
func (*Service) RunExport ¶
func (s *Service) RunExport(ctx context.Context, opts ExportOptions, cb ProgressFunc) (string, error)
RunExport 执行导出,outputPath 返回最终产物路径
func (*Service) RunImport ¶
func (s *Service) RunImport(ctx context.Context, opts ImportOptions, cb ProgressFunc) (*engine.ImportResult, error)
RunImport 执行导入:返回结果(含精确回滚产物路径,仅 .json 数据包导入且 Rollback=true)
func (*Service) RunMigrate ¶
func (s *Service) RunMigrate(ctx context.Context, opts MigrateOptions, cb ProgressFunc) error
RunMigrate 执行迁移
func (*Service) RunSQLScript ¶
func (s *Service) RunSQLScript(ctx context.Context, connKey, dbName, sql string, limit, offset int, mode string) ([]*engine.SQLQueryResult, error)
RunSQLScript 批量执行多语句 SQL(Navicat 式):按分号分割,逐条判断读写并执行, 返回结果集数组(顺序与语句一致)。mode 控制执行模式(transform/raw)。 写操作的安全确认由调用方(前端)在进入本函数前完成。 均写入「SQL 执行历史」并追加审计日志(用户手写,来源 manual)。
func (*Service) RunSnapshotCompareRecorded ¶
func (s *Service) RunSnapshotCompareRecorded(ctx context.Context, snap *Snapshot, target *DBConnInfo, opts SnapshotCompareOptions, cb ProgressFunc) (string, *CompareResult, error)
RunSnapshotCompareRecorded 同步执行快照对比并记录历史(CLI 使用)。 StoreNone 库模式(persist 为 nil)下跳过历史与结果落盘,结果直接由内存返回。
func (*Service) RunTaskByID ¶
RunTaskByID 以保存的任务配置异步执行,返回 taskID
func (*Service) SQLAudit ¶
func (s *Service) SQLAudit(user, connID string, limit, offset int) ([]SQLAuditEntry, error)
SQLAudit 读取某用户域的审计日志(倒序,分页)。审计只读、不提供删除。 connID 为空时按 user 列等值过滤,返回该用户域全部连接数据(跨用户隔离由 user 列保证,非用户域前缀过滤、非全表);connID 非空时按 user 列 + conn_key 双条件过滤;limit<=0 时默认 100,上限 500。
func (*Service) SQLHistory ¶
func (s *Service) SQLHistory(user, connID string) []SQLHistoryItem
SQLHistory 返回某用户域下某连接的历史记录
func (*Service) SaveConfig ¶
SaveConfig 将修改后的全局配置写回 config.yaml。 目录项中,data 根目录固定(已打开的 SQLite 位置不变);其余目录保存后立即热生效。 访问白名单由 handleSaveConfig 额外刷新过滤器。
func (*Service) SaveTask ¶
func (s *Service) SaveTask(task *TaskConfig) error
SaveTask 保存任务配置(新增或更新),并标记为最近使用
func (*Service) SaveWorkspace ¶
func (s *Service) SaveWorkspace(user, connID string, state WorkspaceState) error
SaveWorkspace 保存某用户域下某连接的工作区(整体覆盖)。
func (*Service) StartCompare ¶
func (s *Service) StartCompare(opts CompareOptions, taskConfigID string) (string, error)
StartCompare 异步启动对比任务,返回 taskID;完成后结果报告落盘 CompareDir/compare-<taskID>.json
func (*Service) StartDictionary ¶
func (s *Service) StartDictionary(opts DictionaryOptions, taskConfigID string) (string, error)
StartDictionary 异步启动数据字典任务,返回 taskID;摘要口径为 "X库Y表, 大小"(字典无行数)
func (*Service) StartExport ¶
func (s *Service) StartExport(opts ExportOptions, taskConfigID string) (string, error)
StartExport 异步启动导出任务,返回 taskID
func (*Service) StartImport ¶
func (s *Service) StartImport(opts ImportOptions, taskConfigID string) (string, error)
StartImport 异步启动导入任务,返回 taskID
func (*Service) StartMigrate ¶
func (s *Service) StartMigrate(opts MigrateOptions, taskConfigID string) (string, error)
StartMigrate 异步启动迁移任务,返回 taskID
func (*Service) StartSnapshotCompare ¶
func (s *Service) StartSnapshotCompare(opts SnapshotCompareOptions, taskConfigID string) (string, error)
StartSnapshotCompare 异步启动快照对比任务
func (*Service) TestConnection ¶
func (s *Service) TestConnection(ctx context.Context, conn DBConnInfo) error
TestConnection 测试连接可用性
func (*Service) UpdateTableCell ¶
func (s *Service) UpdateTableCell(ctx context.Context, connKey, dbName string, p engine.UpdateCellParams) (int64, error)
UpdateTableCell 更新表浏览视图中的单个单元格(named bind + 标识符引用,防注入)。 仅用于对象树表浏览(表结构/主键明确)场景;返回影响行数。
type Snapshot ¶
Snapshot 快照完整数据
func LoadSnapshotFile ¶
LoadSnapshotFile 从任意路径读取快照完整数据(离线读文件,不需要连接)。 库模式 LoadSnapshot 门面入口使用;应用模式内的按 ID 读取仍走 loadSnapshot。
type SnapshotCompareOptions ¶
type SnapshotCompareOptions = store.SnapshotCompareOptions
SnapshotCompareOptions 快照对比选项
type SvcError ¶
type SvcError struct {
Code int // cygin 错误码(0 表示由包装方决定,如 cyginWrapAI)
Key string // 错误注册表模板 key
Args []any // 模板参数
Cause error // 底层原因(原 ": %w" 包装),可为 nil
}
SvcError 结构化业务错误
type TaskHooks ¶
type TaskHooks struct {
OnTaskStart func(info TaskStartInfo)
OnTaskProgress func(taskID string, p ProgressInfo)
}
TaskHooks 任务生命周期回调(任务镜像/通知用,宿主可选注册)。 契约:OnTaskStart 在任务登记完成后、执行 goroutine 启动前同步调用(宿主落库 应快速返回,重活自行起 goroutine);OnTaskProgress 在任务执行 goroutine 中 随进度推送调用(含终态:done/error/cancelled),宿主需自行保证并发安全; 回调内不得再回调 dqex 的 Client 方法。
type TaskRunner ¶
type TaskRunner struct {
// contains filtered or unexported fields
}
TaskRunner 管理异步执行中的任务(进度广播 + 取消)
func (*TaskRunner) Start ¶
func (r *TaskRunner) Start(taskID, taskType, source, title, lang, user string, run func(ctx context.Context, publish ProgressFunc) error)
Start 注册并启动一个异步任务;source 为任务主连接 key、title 为展示标题、user 为 发起人标识(均随 OnTaskStart 钩子透传宿主,详见 TaskHooks 契约);lang 为任务语言(错误终态消息按其渲染)
func (*TaskRunner) Subscribe ¶
func (r *TaskRunner) Subscribe(taskID string) (<-chan ProgressInfo, func(), error)
Subscribe 订阅任务进度,返回进度通道与释放函数
type TaskStartInfo ¶
type TaskStartInfo struct {
TaskID string // dqex 任务 ID
TaskType string // export / dictionary / import / migrate / compare
Source string // 主连接 key(已保存连接名;任务参数直接携带连接时为空)
Title string // 任务展示标题(连接 · 目标 概要)
User string // 任务发起人标识(宿主注入 X-DQEX-User 登录名;独立部署为空/local)
}
TaskStartInfo 任务启动信息(TaskHooks.OnTaskStart 参数)。 只携带 dqex 自身语义(任务类型/连接 key/展示标题),不含任何宿主概念, 宿主自行决定是否以及如何镜像(如按 Source 前缀识别归属环境)。