Documentation
¶
Index ¶
- Constants
- func SetClientOptions(o ClientOptions)
- func TagUntrusted(data map[string]any, fields ...string)
- func WorkflowStatusCodeToInt(code string) int
- type APIError
- type ArchiveConfig
- type ArchiveLog
- type AuthAPI
- func (a *AuthAPI) Login(ctx context.Context, username, password string) (string, string, error)
- func (a *AuthAPI) LoginWithSession(ctx context.Context, username, password string) (sessionID, csrfToken string, err error)
- func (a *AuthAPI) Refresh(ctx context.Context, refreshToken string) (string, error)
- func (a *AuthAPI) Verify(ctx context.Context, token string) error
- type BinlogAPI
- type BinlogListResult
- type BinlogParseParams
- type BinlogParseResult
- type BinlogParseRow
- type BinlogPurgeResult
- type Client
- func (c *Client) APIPath(resource string) string
- func (c *Client) CookieJar() http.CookieJar
- func (c *Client) Delete(ctx context.Context, path string) error
- func (c *Client) ExportSessionCookies() (sessionID, csrfToken string)
- func (c *Client) Get(ctx context.Context, path string) ([]byte, error)
- func (c *Client) GetWithPagination(ctx context.Context, path string) ([]byte, Pagination, error)
- func (c *Client) Host() string
- func (c *Client) InjectSessionCookies(sessionID, csrfToken string)
- func (c *Client) InternalDelete(ctx context.Context, path string) error
- func (c *Client) InternalGet(ctx context.Context, path string) ([]byte, error)
- func (c *Client) InternalPost(ctx context.Context, path string, form url.Values) ([]byte, error)
- func (c *Client) InternalPut(ctx context.Context, path string, form url.Values) ([]byte, error)
- func (c *Client) Mode() string
- func (c *Client) Post(ctx context.Context, path string, body any) ([]byte, error)
- func (c *Client) Put(ctx context.Context, path string, body any) ([]byte, error)
- func (c *Client) RefreshToken() string
- func (c *Client) SessionGet(ctx context.Context, path string) ([]byte, error)
- func (c *Client) SessionPost(ctx context.Context, path string, form url.Values) ([]byte, error)
- func (c *Client) SessionPostExpectRedirect(ctx context.Context, path string, form url.Values) (int, error)
- func (c *Client) SetMode(mode string)
- func (c *Client) SetOTP(otp string)
- func (c *Client) SetSessionCredentials(username, password string)
- func (c *Client) SetTokens(accessToken, refreshToken string)
- type ClientOptions
- type DataDictionaryColumn
- type DataDictionaryTable
- type DataDictionaryTableInfo
- type Group
- type GroupRow
- type Instance
- type InternalPage
- type InternalPaginatedResponse
- type ListResult
- type LockInfo
- type PaginatedResponse
- type Pagination
- type ProcessInfo
- type QueryLog
- type QueryResult
- type ResourceGroup
- type ResourceGroupObjectType
- type ResourceGroupRow
- type SQLCheckResult
- type SQLWorkflow
- type SQLWorkflowAuditEntry
- type SQLWorkflowDetail
- type SlowQuery
- type SlowQueryHistory
- type TableSpace
- type TransactionInfo
- type User
- type UserAPI
- func (u *UserAPI) AddResourceGroupRelation(ctx context.Context, groupID int, objectType ResourceGroupObjectType, ...) error
- func (u *UserAPI) ListGroups(ctx context.Context, limit, offset int) ([]GroupRow, int, error)
- func (u *UserAPI) ListResourceGroups(ctx context.Context, limit, offset int, search string) ([]ResourceGroupRow, int, error)
- func (u *UserAPI) ListUsers(ctx context.Context) ([]UserRow, error)
- type UserRow
- type Workflow
- type WorkflowAPI
- func (w *WorkflowAPI) Audit(ctx context.Context, req WorkflowAuditRequest) error
- func (w *WorkflowAPI) Cancel(ctx context.Context, req WorkflowCancelRequest) error
- func (w *WorkflowAPI) Detail(ctx context.Context, id int) (*SQLWorkflowDetail, error)
- func (w *WorkflowAPI) Execute(ctx context.Context, req WorkflowExecuteRequest) error
- func (w *WorkflowAPI) List(ctx context.Context, params WorkflowListParams) (*ListResult[SQLWorkflow], error)
- func (w *WorkflowAPI) SQLCheck(ctx context.Context, req WorkflowSQLCheckRequest) ([]SQLCheckResult, error)
- func (w *WorkflowAPI) Submit(ctx context.Context, req WorkflowSubmitRequest) (*WorkflowSubmitResponse, error)
- type WorkflowAudit
- type WorkflowAuditRequest
- type WorkflowCancelRequest
- type WorkflowContent
- type WorkflowExecuteRequest
- type WorkflowListParams
- type WorkflowSQLCheckRequest
- type WorkflowSubmitRequest
- type WorkflowSubmitResponse
Constants ¶
const ( ModeSession = "session" ModeJWT = "jwt" )
Transport modes mirror config.ModeSession / config.ModeJWT. Session is the default: works for ordinary accounts via Archery's AJAX endpoints + Django session cookie. JWT is the opt-in REST transport.
const APIBasePath = "/api"
APIBasePath is the Archery REST API base path.
const Code2FARequired = "E_2FA_REQUIRED"
Code2FARequired is the sentinel APIError.Code value set when a login is blocked on a missing 2FA code. The cmd layer maps it to output.E_2FA_REQUIRED + the human-required exit code; carrying it as a plain string keeps the api package free of an output dependency.
const CodeValidation = "E_VALIDATION"
CodeValidation is the APIError.Code for a client-side validation failure (e.g. a wrong/expired 2FA code). It mirrors output.E_VALIDATION as a plain string.
const WorkflowTypeSQLReview = 2
WorkflowTypeSQLReview is Archery's workflow_type for SQL上线申请 (SQL-review workflows), the only type the execute command targets.
Variables ¶
This section is empty.
Functions ¶
func SetClientOptions ¶
func SetClientOptions(o ClientOptions)
SetClientOptions updates global HTTP settings (from cmd flags).
func TagUntrusted ¶
TagUntrusted adds a "_untrusted" key to data listing the names of fields that contain externally-sourced, user-generated content. Callers must pass only the inner data map (not the full envelope). Fields that do not exist in the map are silently skipped.
func WorkflowStatusCodeToInt ¶ added in v1.0.4
WorkflowStatusCodeToInt maps Archery's session status string codes to the integer status used by the REST serializer and the CLI's status badges, so both transports render the same label. Unknown codes map to -1.
Types ¶
type APIError ¶
type APIError struct {
StatusCode int
ErrorMessages []string
Errors map[string]string
// Code, when non-empty, is an explicit error-code override the cmd layer uses
// instead of deriving the code from StatusCode (e.g. Code2FARequired).
Code string
}
APIError represents an error returned by the Archery API.
type ArchiveConfig ¶
type ArchiveConfig struct {
ID int `json:"id"`
Title string `json:"title"`
AuditWorkflow int `json:"audit_workflow"`
AuditUsers string `json:"audit_users"`
SourceHost string `json:"source_host"`
SourceDb string `json:"source_db"`
SourceTable string `json:"source_table"`
TargetHost string `json:"target_host"`
TargetDb string `json:"target_db"`
TargetTable string `json:"target_table"`
Mode string `json:"mode"`
Condition string `json:"condition"`
IsArchive bool `json:"is_archive"`
ExecDate string `json:"exec_date"`
Status int `json:"status"`
}
ArchiveConfig represents an archive task configuration.
type ArchiveLog ¶
type ArchiveLog struct {
ID int `json:"id"`
ConfigID int `json:"config_id"`
SQLText string `json:"sql"`
ExecTime string `json:"exec_time"`
Status int `json:"status"`
RowsMoved int `json:"rows_moved"`
ElapsedTime string `json:"elapsed_time"`
}
ArchiveLog represents a single archive execution log.
type AuthAPI ¶
type AuthAPI struct {
// contains filtered or unexported fields
}
AuthAPI wraps authentication-related API calls.
func (*AuthAPI) Login ¶
Login authenticates with username and password, storing tokens on success.
POST /api/auth/token/ Request: {"username": "...", "password": "..."} Response: {"access": "...", "refresh": "..."}
func (*AuthAPI) LoginWithSession ¶
func (a *AuthAPI) LoginWithSession(ctx context.Context, username, password string) (sessionID, csrfToken string, err error)
LoginWithSession authenticates via Archery's session-based AJAX login and returns the resulting Django cookies for caching.
Flow (verified against v1.8.5):
GET /login/ -> Set-Cookie csrftoken
POST /authenticate/ form username/password/csrfmiddlewaretoken
+ headers X-CSRFToken, Referer -> {"status":0,"msg":"ok"} + sessionid
On success the cookie jar holds sessionid + (rotated) csrftoken, which are returned for persistence.
type BinlogAPI ¶ added in v1.0.4
type BinlogAPI struct {
// contains filtered or unexported fields
}
BinlogAPI provides methods for the MySQL binlog endpoints.
These views are session-only: Archery exposes no REST/JWT equivalent under /api/v1/, so every method uses the session (AJAX/Django) transport regardless of the client's mode. Form fields and response shapes are taken from sql/binlog.py in the v1.8.5 source.
func (*BinlogAPI) List ¶ added in v1.0.4
List returns the binary logs of an instance.
session: POST /binlog/list/ (instance_name)
func (*BinlogAPI) Parse ¶ added in v1.0.4
func (b *BinlogAPI) Parse(ctx context.Context, p BinlogParseParams) (*BinlogParseResult, error)
Parse runs the my2sql engine over a binlog range and returns the first `num` statements (rollback statements when Rollback is set).
session: POST /binlog/my2sql/
List fields use the suffixed keys the Django view reads with getlist: only_schemas, only_tables[], sql_type[]. Time fields are start_time and stop_time (the view has no end_time). Booleans are the literal string "true".
func (*BinlogAPI) Purge ¶ added in v1.0.4
func (b *BinlogAPI) Purge(ctx context.Context, instanceID, binlogFile string) (*BinlogPurgeResult, error)
Purge runs `purge master logs to '<binlog>'` on an instance, deleting that file and all binlogs before it.
session: POST /binlog/del_log/ (instance_id, binlog)
Note the view keys the instance by numeric id, not name.
type BinlogListResult ¶ added in v1.0.4
type BinlogListResult struct {
Status int `json:"status"`
Msg string `json:"msg"`
Data []map[string]any `json:"data"`
}
BinlogListResult is the decoded response of POST /binlog/list/.
The view runs `show binary logs;` and returns each row as a map keyed by the result columns (Log_name, File_size, and Encrypted on 8.0). Rows are kept as generic maps because the column set varies across MySQL versions.
type BinlogParseParams ¶ added in v1.0.4
type BinlogParseParams struct {
InstanceName string
StartFile string
EndFile string
StartPos int
EndPos int
StartTime string
StopTime string
Schemas []string // -> only_schemas (repeated)
Tables []string // -> only_tables[] (repeated)
SQLTypes []string // -> sql_type[] (repeated)
Num int
Threads int
Rollback bool
SaveSQL bool
}
BinlogParseParams collects the my2sql request fields. Zero-valued numeric fields are sent as empty strings (see emptyIfZero) so the view applies its own defaults (num=30, threads=4) without 500ing on int(None); an empty sql_type list lets the view default to all DML.
type BinlogParseResult ¶
type BinlogParseResult struct {
Status int `json:"status"`
Msg string `json:"msg"`
Data json.RawMessage `json:"data"`
}
BinlogParseResult is the decoded response of POST /binlog/my2sql/.
data is kept raw because its shape depends on status: the success path sets it to a list of parsed rows, while the arg-check failure path returns {"status":1,"data":{}} (an object). Rows() decodes the list only when the call succeeded, so an error envelope never causes an unmarshal failure.
func (*BinlogParseResult) Rows ¶ added in v1.0.4
func (r *BinlogParseResult) Rows() ([]BinlogParseRow, error)
Rows decodes the parsed statements from a successful response. It returns an empty slice for any non-list data payload (e.g. the {} returned on error).
type BinlogParseRow ¶ added in v1.0.4
type BinlogParseRow struct {
SQL string `json:"sql"`
BinlogInfo string `json:"binlog_info,omitempty"`
}
BinlogParseRow is a single parsed statement. The my2sql engine returns only the SQL text; the binlog2sql engine also fills BinlogInfo (position metadata).
type BinlogPurgeResult ¶ added in v1.0.4
BinlogPurgeResult is the decoded response of POST /binlog/del_log/.
The view returns status 0 on success, 1 when no binlog was given, and 2 when the `purge master logs` statement failed.
type Client ¶
type Client struct {
Auth *AuthAPI
Workflows *WorkflowAPI
Binlog *BinlogAPI
Users *UserAPI
// contains filtered or unexported fields
}
Client wraps the Archery API HTTP client.
func NewClient ¶
NewClient creates a new API client using global HTTP options. The transport defaults to session mode; callers switch to JWT via SetMode(ModeJWT).
func (*Client) ExportSessionCookies ¶ added in v1.0.4
ExportSessionCookies returns the current sessionid and csrftoken from the jar, for persistence after a successful login. Either value may be empty.
func (*Client) GetWithPagination ¶
GetWithPagination sends a GET request and returns body + pagination metadata from the response headers. Useful for list endpoints.
func (*Client) InjectSessionCookies ¶ added in v1.0.4
InjectSessionCookies seeds the cookie jar with cached Django cookies so that session requests can skip the interactive form login. Empty values are ignored. When a sessionid is present the client is marked ready, avoiding a redundant /authenticate/ round-trip on the first call.
func (*Client) InternalDelete ¶
InternalDelete sends a DELETE request with session cookie auth.
func (*Client) InternalGet ¶
InternalGet sends a GET request with session cookie auth.
func (*Client) InternalPost ¶
InternalPost sends a POST request with session cookie auth.
func (*Client) InternalPut ¶
InternalPut sends a PUT request with session cookie auth.
func (*Client) RefreshToken ¶
RefreshToken returns the current refresh token.
func (*Client) SessionGet ¶ added in v1.0.4
SessionGet sends a GET request with Django session cookie auth. Canonical name for the default (session) transport; InternalGet is kept as an alias used throughout the command layer.
func (*Client) SessionPost ¶ added in v1.0.4
SessionPost sends a form-encoded POST with Django session cookie auth.
func (*Client) SessionPostExpectRedirect ¶ added in v1.0.4
func (c *Client) SessionPostExpectRedirect(ctx context.Context, path string, form url.Values) (int, error)
SessionPostExpectRedirect posts a form to a Django view that signals success with a 302 redirect to the new object's detail page, and returns the object id parsed from the Location header (e.g. /detail/42/ -> 42). Archery's submit views render error.html with HTTP 200 on a validation failure instead of redirecting, so a 200 (non-redirect) is reported as an error carrying the page's message hint. This does not follow the redirect: the id is in the Location header, and following it would lose it.
func (*Client) SetMode ¶ added in v1.0.4
SetMode selects the transport: ModeSession (default) or ModeJWT. Any other value falls back to session.
func (*Client) SetOTP ¶ added in v1.0.5
SetOTP supplies a 6-digit 2FA code used to complete login for accounts with two-factor authentication enabled. Empty means "no code provided": ensureSession then surfaces an E_2FA_REQUIRED error when the account demands one.
func (*Client) SetSessionCredentials ¶
SetSessionCredentials supplies the username/password used to establish a Django session for internal-mode (legacy web endpoint) commands. JWT-only configs (keyring) leave these empty; ensureSession then returns a clear error directing the caller to provide credentials.
type ClientOptions ¶
ClientOptions configures HTTP transport settings.
func CurrentClientOptions ¶
func CurrentClientOptions() ClientOptions
CurrentClientOptions returns the global HTTP settings (for tests/diagnostics).
type DataDictionaryColumn ¶
type DataDictionaryColumn struct {
ColumnName string `json:"column_name"`
ColumnType string `json:"column_type"`
ColumnComment string `json:"column_comment"`
IsNullable string `json:"is_nullable"`
ColumnKey string `json:"column_key"`
ColumnDefault any `json:"column_default"`
}
DataDictionaryColumn describes a single column in a data dictionary table.
type DataDictionaryTable ¶
type DataDictionaryTable struct {
ID int `json:"id"`
Name string `json:"name"`
Comment string `json:"comment"`
InstanceID int `json:"instance_id"`
DBName string `json:"db_name"`
TableName string `json:"table_name"`
IsPublished bool `json:"is_published"`
}
DataDictionaryTable represents a table entry in the data dictionary.
type DataDictionaryTableInfo ¶
type DataDictionaryTableInfo struct {
TableName string `json:"table_name"`
Comment string `json:"comment"`
Columns []DataDictionaryColumn `json:"columns"`
}
DataDictionaryTableInfo holds detailed column info for a dictionary table.
type Instance ¶
type Instance struct {
ID json.Number `json:"id"`
InstanceName string `json:"instance_name"`
DbType string `json:"db_type"`
Host string `json:"host"`
Port int `json:"port"`
User string `json:"user"`
Password string `json:"password"`
DBName string `json:"db_name"`
Charset string `json:"charset"`
IsActive bool `json:"is_active"`
Environment string `json:"environment"`
// Archery's instance_tag is a ManyToMany relation serialized as an array,
// not a string (empty M2M -> []).
InstanceTag []any `json:"instance_tag"`
}
Instance represents a database instance configured in Archery.
type InternalPage ¶
InternalPage holds the pagination payload for internal endpoints.
type InternalPaginatedResponse ¶
type InternalPaginatedResponse[T any] struct { Status int `json:"status"` Msg string `json:"msg"` Data InternalPage[T] `json:"data"` }
InternalPaginatedResponse wraps Archery internal paginated responses that use {status, msg, data: {total, rows}} format.
type ListResult ¶
type ListResult[T any] struct { Page PaginatedResponse[T] Pagination Pagination }
ListResult holds the parsed response and pagination metadata for a list call.
type LockInfo ¶
type LockInfo struct {
LockTrxID string `json:"lock_trx_id"`
LockMode string `json:"lock_mode"`
LockType string `json:"lock_type"`
LockTable string `json:"lock_table"`
LockIndex string `json:"lock_index"`
LockSpace int `json:"lock_space"`
LockPage int `json:"lock_page"`
LockRec int `json:"lock_rec"`
LockData string `json:"lock_data"`
TrxID string `json:"trx_id"`
TrxState string `json:"trx_state"`
TrxStarted string `json:"trx_started"`
TrxQuery string `json:"trx_query"`
TrxWait int `json:"trx_wait"`
}
LockInfo represents an InnoDB lock entry.
type PaginatedResponse ¶
type PaginatedResponse[T any] struct { Count int `json:"count"` Next any `json:"next"` Previous any `json:"previous"` Results []T `json:"results"` }
PaginatedResponse wraps DRF paginated list responses.
type Pagination ¶
type Pagination struct {
// Count is the total number of items (from X-Total-Count header or JSON "count").
Count int
// Page is the current page number (from X-Page header, 1-based).
Page int
// PerPage is the page size (from X-Per-Page header).
PerPage int
// NextPage is the next page number (0 if last page).
NextPage int
// PrevPage is the previous page number (0 if first page).
PrevPage int
// Link is the raw Link header value (RFC 5988).
Link string
}
Pagination holds page metadata from DRF response headers or response body.
Archery uses Django REST Framework. Depending on the paginator configured server-side, pagination info may arrive as:
- HTTP headers: X-Total-Count, Link (RFC 5988)
- JSON body: {"count": N, "next": "url", "previous": "url", "results": [...]}
This struct captures both sources. The JSON-body fields (Count, Next, Previous) come from PaginatedResponse; the header fields are populated by extractPagination when the caller uses GetWithPagination.
type ProcessInfo ¶
type ProcessInfo struct {
ID int `json:"id"`
User string `json:"user"`
Host string `json:"host"`
DB string `json:"db"`
Command string `json:"command"`
Time int `json:"time"`
State string `json:"state"`
Info string `json:"info"`
}
ProcessInfo represents a MySQL process list entry.
type QueryLog ¶
type QueryLog struct {
ID int `json:"id"`
Username string `json:"username"`
DbUser string `json:"db_user"`
SQLText string `json:"sqllog"`
EffectRows int `json:"effect_row"`
CostTime string `json:"cost_time"`
Instance string `json:"instance_name"`
ExecTime string `json:"exec_time"`
}
QueryLog represents a single query log entry.
type QueryResult ¶
type QueryResult struct {
Rows []map[string]any `json:"rows"`
ColumnNames []string `json:"column_names"`
RowCount int `json:"row_count"`
AffectedRows int `json:"affected_rows"`
IsExecute bool `json:"is_execute"`
ErrorMessage string `json:"error_message"`
}
QueryResult holds the result of a SQL query execution.
type ResourceGroup ¶
type ResourceGroup struct {
ID int `json:"id"`
Name string `json:"name"`
Users []int `json:"users"`
}
ResourceGroup represents a resource group for instance access control.
type ResourceGroupObjectType ¶ added in v1.0.4
type ResourceGroupObjectType string
ResourceGroupObjectType selects which relation a resourcegroup-add mutation targets: users or instances. Archery's view encodes these as the string "0" and "1" respectively.
const ( ResourceGroupObjectUser ResourceGroupObjectType = "0" ResourceGroupObjectInstance ResourceGroupObjectType = "1" )
type ResourceGroupRow ¶ added in v1.0.4
ResourceGroupRow is a resource group used for instance access control. The session projection carries only the id/name (and ding webhook); the REST serializer additionally reports active/bind user counts, left zero in session mode.
type SQLCheckResult ¶
type SQLCheckResult struct {
Level string `json:"level"`
Message string `json:"message"`
AffectedRows int `json:"affected_rows"`
SQL string `json:"sql"`
ErrLevel int `json:"errlevel"`
StageStatus string `json:"stagestatus,omitempty"`
}
SQLCheckResult is a single item from the SQL check response. Level/Message are the REST serializer's fields; ErrLevel/StageStatus come from the session ReviewResult and drive auto-review classification (errlevel: 0 ok, 1 warning, 2 error). When the session transport fills the result, Level is derived from ErrLevel so existing badge rendering keeps working.
type SQLWorkflow ¶
type SQLWorkflow struct {
ID int `json:"id"`
Title string `json:"workflow_name"`
Status int `json:"status"`
StatusCode string `json:"-"`
Engineer string `json:"engineer"`
InstanceID int `json:"instance_id"`
InstanceName string `json:"-"`
DBName string `json:"db_name"`
GroupID int `json:"group_id"`
GroupName string `json:"-"`
CreateDate string `json:"create_date"`
}
SQLWorkflow is a single row from the workflow list endpoint. It is the common shape both transports map into: the REST serializer fills the numeric fields (Status, InstanceID, GroupID), while the session projection fills StatusCode (the string status), InstanceName and GroupName. The unset side stays zero.
type SQLWorkflowAuditEntry ¶
type SQLWorkflowAuditEntry struct {
User string `json:"audit_user"`
Action string `json:"audit_type"`
Remark string `json:"remark"`
CreateDate string `json:"create_date"`
}
SQLWorkflowAuditEntry is a single audit log entry within a workflow detail.
type SQLWorkflowDetail ¶
type SQLWorkflowDetail struct {
ID int `json:"id"`
Title string `json:"workflow_name"`
Status int `json:"status"`
Engineer string `json:"engineer"`
InstanceID int `json:"instance_id"`
DBName string `json:"db_name"`
GroupID int `json:"group_id"`
SQLContent string `json:"sql_content"`
IsBackup bool `json:"is_backup"`
DemandURL string `json:"demand_url"`
CreateDate string `json:"create_date"`
AuditLog []SQLWorkflowAuditEntry `json:"audit_log"`
// 以下字段来自 session 路径的组合查询(detail_content + 列表),不来自单一 JSON 端点。
// StatusCode 是字符串状态码(如 workflow_exception),从工单列表取,
// 避免 detail 把缺省 status 误报成 0。
StatusCode string `json:"-"`
InstanceName string `json:"-"`
GroupName string `json:"-"`
// Result 是执行/审核结果行(含 stage、errlevel、errormessage、affected_rows),
// 来自 /sqlworkflow/detail_content/,是「执行失败看原因」的关键数据。
Result []reviewResultRow `json:"-"`
}
SQLWorkflowDetail is the full detail of an SQL workflow.
type SlowQuery ¶
type SlowQuery struct {
ID int `json:"id"`
SQLText string `json:"sql_text"`
MySQLTotal float64 `json:"mysql_total"`
Count int `json:"count"`
MaxQueryTime float64 `json:"max_query_time"`
MysqlMaxTime float64 `json:"mysql_max_time"`
}
SlowQuery represents a slow query entry from the analysis system.
type SlowQueryHistory ¶
type SlowQueryHistory struct {
ID int `json:"id"`
SlowQueryID int `json:"slowquery_id"`
SQLText string `json:"sql_text"`
StartTime string `json:"start_time"`
StopTime string `json:"stop_time"`
QueryTimeAvg float64 `json:"query_time_avg"`
LockTimeAvg float64 `json:"lock_time_avg"`
RowsExamined int `json:"rows_examined_avg"`
RowsSent int `json:"rows_sent_avg"`
}
SlowQueryHistory represents historical slow query data.
type TableSpace ¶
type TableSpace struct {
TableName string `json:"table_name"`
Engine string `json:"engine"`
RowFormat string `json:"row_format"`
Rows int `json:"table_rows"`
DataSize string `json:"data_length"`
IndexSize string `json:"index_length"`
TotalSize string `json:"total_size"`
}
TableSpace represents table space usage information.
type TransactionInfo ¶
type TransactionInfo struct {
TrxID string `json:"trx_id"`
TrxState string `json:"trx_state"`
TrxStarted string `json:"trx_started"`
TrxQuery string `json:"trx_query"`
TrxRowsLocked int `json:"trx_rows_locked"`
TrxRowsModified int `json:"trx_rows_modified"`
}
TransactionInfo represents a running transaction.
type User ¶
type User struct {
ID int `json:"id"`
Username string `json:"username"`
Display string `json:"display"`
Email string `json:"email"`
IsActive bool `json:"is_active"`
IsStaff bool `json:"is_staff"`
Groups []int `json:"groups"`
}
User represents an Archery user.
type UserAPI ¶ added in v1.0.4
type UserAPI struct {
// contains filtered or unexported fields
}
UserAPI provides methods for the user / group / resource-group endpoints.
Each method branches on the client transport mode. Session mode (the default) targets Archery's AJAX/Django endpoints that ordinary accounts can reach; JWT mode targets the REST API under /api/v1/. The session shapes are taken from sql/user.py and sql/resource_group.py in the v1.8.5 source.
func (*UserAPI) AddResourceGroupRelation ¶ added in v1.0.4
func (u *UserAPI) AddResourceGroupRelation(ctx context.Context, groupID int, objectType ResourceGroupObjectType, objectIDs []int) error
AddResourceGroupRelation associates users or instances with a resource group.
session: POST /group/addrelation/ (group_id, object_type, object_info)
object_info is a JSON-encoded array of strings; the view splits each element on "," and takes the leading integer as the object id (matching the web UI's "id,name" rows). This is a session-only operation: there is no REST/JWT route for it in v1.8.5, so the call uses the session transport regardless of mode.
func (*UserAPI) ListGroups ¶ added in v1.0.4
ListGroups returns Django auth (permission) groups via the REST endpoint.
jwt: GET /api/v1/user/group/?limit&offset
Session mode has no JSON route in v1.8.5: the web page /group/ renders HTML, not a list payload. The caller gates session mode before reaching here.
func (*UserAPI) ListResourceGroups ¶ added in v1.0.4
func (u *UserAPI) ListResourceGroups(ctx context.Context, limit, offset int, search string) ([]ResourceGroupRow, int, error)
ListResourceGroups returns resource groups.
session: POST /group/group/ (limit, offset, search) jwt: GET /api/v1/user/resourcegroup/?limit&offset&search
func (*UserAPI) ListUsers ¶ added in v1.0.4
ListUsers returns all users.
session: GET /user/list/ (no params; returns the full list) jwt: GET /api/v1/user/?limit&offset&search
The session view (user.lists) does no server-side pagination or search, so those filters are applied client-side by the caller.
type UserRow ¶ added in v1.0.4
type UserRow struct {
ID int
Username string
Display string
Email string
IsActive bool
IsStaff bool
IsSuperuser bool
}
UserRow is the common shape both transports map into. The session projection (user.lists) fills IsSuperuser; the REST serializer does not expose it, so the unset side stays zero/false.
type Workflow ¶
type Workflow struct {
ID int `json:"id"`
Name string `json:"name"`
IsUsed bool `json:"is_used"`
Content []WorkflowContent `json:"content"`
}
Workflow represents an Archery workflow definition (template).
type WorkflowAPI ¶
type WorkflowAPI struct {
// contains filtered or unexported fields
}
WorkflowAPI provides methods for the SQL workflow endpoints.
Each method branches on the client transport mode. Session mode (the default) targets Archery's AJAX/Django endpoints, which ordinary accounts can reach; JWT mode targets the REST API under /api/v1/. The session shapes are taken from sql/sql_workflow.py in the v1.8.5 source.
func (*WorkflowAPI) Audit ¶
func (w *WorkflowAPI) Audit(ctx context.Context, req WorkflowAuditRequest) error
Audit approves a workflow (audit pass). Cancel/reject goes through Cancel.
session: POST /passed/ (workflow_id + audit_remark; requires auditor) jwt: POST /api/v1/workflow/audit/
func (*WorkflowAPI) Cancel ¶
func (w *WorkflowAPI) Cancel(ctx context.Context, req WorkflowCancelRequest) error
Cancel terminates a workflow.
session: POST /cancel/ (workflow_id + cancel_remark)
The session field is cancel_remark and the view requires it to be present (a nil value renders "终止原因不能为空"). There is no REST cancel endpoint.
func (*WorkflowAPI) Detail ¶
func (w *WorkflowAPI) Detail(ctx context.Context, id int) (*SQLWorkflowDetail, error)
Detail fetches workflow details. v1.8.5 has no REST detail endpoint (/api/v1/workflow/<id>/ -> 404), so both modes read the session view.
GET /sqlworkflow/detail_content/?workflow_id=<id>
The view returns {"rows":[ReviewResult...]} — the SQL check / execution result rows, not workflow metadata (no such metadata endpoint exists in v1.8.5). SQL content is reconstructed from the rows. List rows carry the metadata (title/status/engineer) when the caller has them.
func (*WorkflowAPI) Execute ¶
func (w *WorkflowAPI) Execute(ctx context.Context, req WorkflowExecuteRequest) error
Execute starts execution of an approved workflow.
session: POST /execute/ (workflow_id + mode; requires execute permission) jwt: POST /api/v1/workflow/execute/
func (*WorkflowAPI) List ¶
func (w *WorkflowAPI) List(ctx context.Context, params WorkflowListParams) (*ListResult[SQLWorkflow], error)
List returns a paginated list of SQL workflows.
session: POST /sqlworkflow_list/ (or /sqlworkflow_list_audit/ when Audit) jwt: GET /api/v1/workflow/
func (*WorkflowAPI) SQLCheck ¶
func (w *WorkflowAPI) SQLCheck(ctx context.Context, req WorkflowSQLCheckRequest) ([]SQLCheckResult, error)
SQLCheck runs SQL syntax and risk checks without creating a workflow.
session: POST /simplecheck/ (instance_name + db_name + sql_content) jwt: POST /api/v1/workflow/sqlcheck/
func (*WorkflowAPI) Submit ¶
func (w *WorkflowAPI) Submit(ctx context.Context, req WorkflowSubmitRequest) (*WorkflowSubmitResponse, error)
Submit creates a new SQL workflow.
session: POST /autoreview/ (names; is_backup as "True"/"False"; 302 redirect) jwt: POST /api/v1/workflow/
type WorkflowAudit ¶
type WorkflowAudit struct {
ID int `json:"id"`
Title string `json:"title"`
Workflow int `json:"workflow"`
WorkflowType int `json:"workflow_type"`
Status int `json:"status"`
CurrentStep int `json:"current_step"`
CreateUser string `json:"create_user"`
CreateDate string `json:"create_date"`
InstanceId int `json:"instance_id"`
}
WorkflowAudit represents a pending workflow audit entry.
type WorkflowAuditRequest ¶
type WorkflowAuditRequest struct {
WorkflowID int `json:"workflow_id"`
Action string `json:"audit_type"`
// Archery's AuditWorkflowSerializer names this audit_remark and treats it as
// required; sending "remark" left it empty and the API rejected the audit.
Remark string `json:"audit_remark"`
}
WorkflowAuditRequest is the payload for POST /api/v1/workflow/audit/.
type WorkflowCancelRequest ¶
type WorkflowCancelRequest struct {
WorkflowID int `json:"workflow_id"`
Remark string `json:"remark,omitempty"`
}
WorkflowCancelRequest is the payload for POST /sqlworkflow/cancel/.
type WorkflowContent ¶
type WorkflowContent struct {
Step int `json:"step"`
Assignee int `json:"assignee"`
AuditAuthGroups string `json:"audit_auth_groups"`
}
WorkflowContent is a single step in a workflow definition.
type WorkflowExecuteRequest ¶
type WorkflowExecuteRequest struct {
WorkflowID int `json:"workflow_id"`
WorkflowType int `json:"workflow_type"`
Engineer string `json:"engineer,omitempty"`
Mode string `json:"mode"`
}
WorkflowExecuteRequest is the payload for POST /api/v1/workflow/execute/.
Archery's ExecuteWorkflowSerializer requires workflow_type and, for SQL-review workflows (type 2), engineer + mode — not just workflow_id. WorkflowType defaults to 2 (SQL上线申请); Engineer is the authenticated operator.
type WorkflowListParams ¶
type WorkflowListParams struct {
Status string
Engineer string
InstanceID int
GroupID int
DBName string
Search string
StartDate string
EndDate string
Limit int
Offset int
Audit bool
}
WorkflowListParams holds query parameters for the workflow list endpoint.
Session and REST transports accept overlapping but not identical filters. The session endpoint (/sqlworkflow_list/) filters on navStatus (the string status code), group_id, instance_id, search (matches engineer/title) and a start/end date range; it has no engineer or db_name filter. REST keeps the engineer/db_name filters it already supported. Audit narrows the list to the current user's pending-audit scope (/sqlworkflow_list_audit/).
type WorkflowSQLCheckRequest ¶
type WorkflowSQLCheckRequest struct {
InstanceID int `json:"instance_id"`
InstanceName string `json:"-"`
DBName string `json:"db_name"`
SQLContent string `json:"sql_content"`
}
WorkflowSQLCheckRequest is the payload for the SQL pre-check. Session (/simplecheck/) uses instance_name; REST uses instance_id. The command fills the identifier the active transport needs.
type WorkflowSubmitRequest ¶
type WorkflowSubmitRequest struct {
Name string `json:"workflow_name"`
InstanceID int `json:"instance_id"`
InstanceName string `json:"-"`
DBName string `json:"db_name"`
SQLContent string `json:"sql_content"`
GroupID int `json:"group_id,omitempty"`
GroupName string `json:"-"`
IsBackup bool `json:"is_backup"`
DemandURL string `json:"demand_url,omitempty"`
CCUsers []string `json:"-"`
RunDateStart string `json:"-"`
RunDateEnd string `json:"-"`
}
WorkflowSubmitRequest is the payload for submitting a workflow.
The two transports key on different identifiers. The session endpoint (/autoreview/) takes names — InstanceName and GroupName — plus is_backup as the string "True"/"False"; the REST endpoint takes the numeric InstanceID and GroupID. The command fills whichever the active mode needs; the API layer reads the matching set. CCUsers and the RunDate* window are session-only optional fields (carbon-copy notify recipients, timed execution).
type WorkflowSubmitResponse ¶
type WorkflowSubmitResponse struct {
ID int `json:"id"`
}
WorkflowSubmitResponse is returned after a successful workflow submission.