Documentation
¶
Overview ¶
Package dbtools provides helper functions and utilities for database operations in the DB MCP Server, including query building, schema exploration, and performance analysis.
Index ¶
- func AnalyzeQuery(query string) []string
- func BeginTx(ctx context.Context, db Database, opts *sql.TxOptions) (*sql.Tx, error)
- func CloseDatabase() error
- func Exec(ctx context.Context, db Database, query string, args ...interface{}) (sql.Result, error)
- func GetDatabase(id string) (db.Database, error)
- func GetDatabaseQueryTimeout(db db.Database) int
- func GetDatabaseType(id string) (string, error)
- func GetTransaction(id string) (*sql.Tx, bool)
- func InitDatabase(cfg *Config) error
- func IsLazyLoading() bool
- func ListDatabases() []string
- func PingDatabase(db *sql.DB) error
- func Query(ctx context.Context, db Database, query string, args ...interface{}) (*sql.Rows, error)
- func QueryRow(ctx context.Context, db Database, query string, args ...interface{}) *sql.Row
- func RegisterDatabaseTools(registry *tools.Registry) error
- func RegisterMCPDatabaseTools(registry *tools.Registry) error
- func RemoveTransaction(id string)
- func StoreTransaction(id string, tx *sql.Tx)
- func StripComments(input string) string
- type Condition
- type Config
- type ConnectionConfig
- type Database
- type DatabaseConnectionInfo
- type DatabaseStrategy
- type DatabaseType
- type GenericStrategy
- type JoinClause
- type MultiDBConfig
- type MySQLStrategy
- type OrderBy
- type PerformanceAnalyzer
- func (pa *PerformanceAnalyzer) GetAllMetrics() []*QueryMetrics
- func (pa *PerformanceAnalyzer) GetSlowThreshold() time.Duration
- func (pa *PerformanceAnalyzer) LogSlowQuery(query string, params []interface{}, duration time.Duration)
- func (pa *PerformanceAnalyzer) Reset()
- func (pa *PerformanceAnalyzer) SetSlowThreshold(threshold time.Duration)
- func (pa *PerformanceAnalyzer) TrackQuery(_ context.Context, query string, params []interface{}, ...) (interface{}, error)
- type PostgresStrategy
- type QueryComponents
- type QueryMetrics
- type QueryRecord
- type QueryWithArgs
- type SQLIssueDetector
- type SQLiteStrategy
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AnalyzeQuery ¶ added in v1.2.0
AnalyzeQuery analyzes a SQL query and returns optimization suggestions
func GetDatabase ¶
GetDatabase returns a database instance by ID
func GetDatabaseQueryTimeout ¶ added in v1.7.0
GetDatabaseQueryTimeout returns the query timeout for a database in milliseconds
func GetDatabaseType ¶ added in v1.9.0
GetDatabaseType returns the type of a database by its ID without establishing a connection
func GetTransaction ¶ added in v1.4.0
GetTransaction retrieves a transaction from the global map
func InitDatabase ¶
InitDatabase initializes the database connections
func IsLazyLoading ¶ added in v1.9.0
func IsLazyLoading() bool
IsLazyLoading returns whether lazy loading mode is currently enabled
func ListDatabases ¶ added in v1.3.0
func ListDatabases() []string
ListDatabases returns a list of available database connections
func PingDatabase ¶ added in v1.3.0
PingDatabase pings a database to check the connection
func RegisterDatabaseTools ¶
RegisterDatabaseTools registers all database tools with the provided registry
func RegisterMCPDatabaseTools ¶ added in v1.7.0
RegisterMCPDatabaseTools registers database tools specifically formatted for MCP compatibility
func RemoveTransaction ¶ added in v1.4.0
func RemoveTransaction(id string)
RemoveTransaction removes a transaction from the global map
func StoreTransaction ¶ added in v1.4.0
StoreTransaction stores a transaction in the global map
func StripComments ¶ added in v1.4.0
StripComments removes SQL comments from a query string
Types ¶
type Condition ¶ added in v1.3.0
type Condition struct {
Column string `json:"column"`
Operator string `json:"operator"`
Value string `json:"value"`
Connector string `json:"connector"`
}
Condition represents a WHERE condition
type Config ¶ added in v1.4.0
type Config struct {
ConfigFile string
Connections []ConnectionConfig
LazyLoading bool // Enable lazy loading: connections established on first use
}
Config represents database configuration
type ConnectionConfig ¶ added in v1.4.0
type ConnectionConfig struct {
ID string `json:"id"`
Type DatabaseType `json:"type"`
Host string `json:"host"`
Port int `json:"port"`
Name string `json:"name"`
User string `json:"user"`
Password string `json:"password"`
// PostgreSQL specific options
SSLMode string `json:"ssl_mode,omitempty"`
SSLCert string `json:"ssl_cert,omitempty"`
SSLKey string `json:"ssl_key,omitempty"`
SSLRootCert string `json:"ssl_root_cert,omitempty"`
ApplicationName string `json:"application_name,omitempty"`
ConnectTimeout int `json:"connect_timeout,omitempty"`
QueryTimeout int `json:"query_timeout,omitempty"` // in seconds
TargetSessionAttrs string `json:"target_session_attrs,omitempty"`
Options map[string]string `json:"options,omitempty"`
// SQLite specific options
DatabasePath string `json:"database_path,omitempty"` // Path to SQLite database file
EncryptionKey string `json:"encryption_key,omitempty"` // Key for SQLCipher encryption
ReadOnly bool `json:"read_only,omitempty"` // Open database in read-only mode
CacheSize int `json:"cache_size,omitempty"` // SQLite cache size (in pages)
JournalMode string `json:"journal_mode,omitempty"` // Journal mode for SQLite
UseModerncDriver bool `json:"use_modernc_driver,omitempty"` // Use modernc.org/sqlite driver instead of mattn/go-sqlite3
// Connection pool settings
MaxOpenConns int `json:"max_open_conns,omitempty"`
MaxIdleConns int `json:"max_idle_conns,omitempty"`
ConnMaxLifetime int `json:"conn_max_lifetime_seconds,omitempty"` // in seconds
ConnMaxIdleTime int `json:"conn_max_idle_time_seconds,omitempty"` // in seconds
}
ConnectionConfig represents a single database connection configuration
type Database ¶
type Database interface {
Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
}
Database represents a database interface This is used in testing to provide a common interface
type DatabaseConnectionInfo ¶ added in v1.3.0
type DatabaseConnectionInfo struct {
ID string `json:"id"`
Type DatabaseType `json:"type"`
Host string `json:"host"`
Port int `json:"port"`
Name string `json:"name"`
Status string `json:"status"`
Latency string `json:"latency,omitempty"`
}
DatabaseConnectionInfo represents detailed information about a database connection
type DatabaseStrategy ¶ added in v1.6.4
type DatabaseStrategy interface {
GetTablesQueries() []QueryWithArgs
GetColumnsQueries(table string) []QueryWithArgs
GetRelationshipsQueries(table string) []QueryWithArgs
}
DatabaseStrategy defines the interface for database-specific query strategies
func NewDatabaseStrategy ¶ added in v1.6.4
func NewDatabaseStrategy(driverName string) DatabaseStrategy
NewDatabaseStrategy creates the appropriate strategy for the given database type
type DatabaseType ¶
type DatabaseType string
DatabaseType represents a supported database type
const ( // MySQL database type MySQL DatabaseType = "mysql" // Postgres database type Postgres DatabaseType = "postgres" )
type GenericStrategy ¶ added in v1.6.4
type GenericStrategy struct{}
GenericStrategy implements DatabaseStrategy for unknown database types
func (*GenericStrategy) GetColumnsQueries ¶ added in v1.6.4
func (s *GenericStrategy) GetColumnsQueries(table string) []QueryWithArgs
GetColumnsQueries returns generic queries for retrieving columns
func (*GenericStrategy) GetRelationshipsQueries ¶ added in v1.6.4
func (s *GenericStrategy) GetRelationshipsQueries(table string) []QueryWithArgs
GetRelationshipsQueries returns generic queries for retrieving relationships
func (*GenericStrategy) GetTablesQueries ¶ added in v1.6.4
func (s *GenericStrategy) GetTablesQueries() []QueryWithArgs
GetTablesQueries returns generic queries for retrieving tables
type JoinClause ¶ added in v1.3.0
type JoinClause struct {
Type string `json:"type"`
Table string `json:"table"`
On string `json:"on"`
}
JoinClause represents a SQL JOIN clause
type MultiDBConfig ¶ added in v1.4.0
type MultiDBConfig struct {
Connections []ConnectionConfig `json:"connections"`
}
MultiDBConfig represents configuration for multiple database connections
type MySQLStrategy ¶ added in v1.6.4
type MySQLStrategy struct{}
MySQLStrategy implements DatabaseStrategy for MySQL
func (*MySQLStrategy) GetColumnsQueries ¶ added in v1.6.4
func (s *MySQLStrategy) GetColumnsQueries(table string) []QueryWithArgs
GetColumnsQueries returns queries for retrieving columns in MySQL
func (*MySQLStrategy) GetRelationshipsQueries ¶ added in v1.6.4
func (s *MySQLStrategy) GetRelationshipsQueries(table string) []QueryWithArgs
GetRelationshipsQueries returns queries for retrieving relationships in MySQL
func (*MySQLStrategy) GetTablesQueries ¶ added in v1.6.4
func (s *MySQLStrategy) GetTablesQueries() []QueryWithArgs
GetTablesQueries returns queries for retrieving tables in MySQL
type PerformanceAnalyzer ¶ added in v1.2.0
type PerformanceAnalyzer struct {
// contains filtered or unexported fields
}
PerformanceAnalyzer tracks query performance and provides optimization suggestions
func GetPerformanceAnalyzer ¶ added in v1.2.0
func GetPerformanceAnalyzer() *PerformanceAnalyzer
GetPerformanceAnalyzer returns the singleton performance analyzer
func NewPerformanceAnalyzer ¶ added in v1.2.0
func NewPerformanceAnalyzer() *PerformanceAnalyzer
NewPerformanceAnalyzer creates a new performance analyzer
func (*PerformanceAnalyzer) GetAllMetrics ¶ added in v1.2.0
func (pa *PerformanceAnalyzer) GetAllMetrics() []*QueryMetrics
GetAllMetrics returns all collected metrics
func (*PerformanceAnalyzer) GetSlowThreshold ¶ added in v1.4.0
func (pa *PerformanceAnalyzer) GetSlowThreshold() time.Duration
GetSlowThreshold returns the current slow query threshold
func (*PerformanceAnalyzer) LogSlowQuery ¶ added in v1.4.0
func (pa *PerformanceAnalyzer) LogSlowQuery(query string, params []interface{}, duration time.Duration)
LogSlowQuery logs a warning if a query takes longer than the slow query threshold
func (*PerformanceAnalyzer) Reset ¶ added in v1.2.0
func (pa *PerformanceAnalyzer) Reset()
Reset clears all collected metrics
func (*PerformanceAnalyzer) SetSlowThreshold ¶ added in v1.2.0
func (pa *PerformanceAnalyzer) SetSlowThreshold(threshold time.Duration)
SetSlowThreshold sets the slow query threshold
func (*PerformanceAnalyzer) TrackQuery ¶ added in v1.2.0
func (pa *PerformanceAnalyzer) TrackQuery(_ context.Context, query string, params []interface{}, exec func() (interface{}, error)) (interface{}, error)
TrackQuery tracks the execution of a query and logs slow queries
type PostgresStrategy ¶ added in v1.6.4
type PostgresStrategy struct{}
PostgresStrategy implements DatabaseStrategy for PostgreSQL
func (*PostgresStrategy) GetColumnsQueries ¶ added in v1.6.4
func (s *PostgresStrategy) GetColumnsQueries(table string) []QueryWithArgs
GetColumnsQueries returns queries for retrieving columns in PostgreSQL
func (*PostgresStrategy) GetRelationshipsQueries ¶ added in v1.6.4
func (s *PostgresStrategy) GetRelationshipsQueries(table string) []QueryWithArgs
GetRelationshipsQueries returns queries for retrieving relationships in PostgreSQL
func (*PostgresStrategy) GetTablesQueries ¶ added in v1.6.4
func (s *PostgresStrategy) GetTablesQueries() []QueryWithArgs
GetTablesQueries returns queries for retrieving tables in PostgreSQL
type QueryComponents ¶ added in v1.3.0
type QueryComponents struct {
Select []string `json:"select"`
From string `json:"from"`
Joins []JoinClause `json:"joins"`
Where []Condition `json:"where"`
GroupBy []string `json:"groupBy"`
Having []string `json:"having"`
OrderBy []OrderBy `json:"orderBy"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
QueryComponents represents the components of a SQL query
type QueryMetrics ¶ added in v1.2.0
type QueryMetrics struct {
Query string // SQL query text
Count int // Number of times the query was executed
TotalDuration time.Duration // Total execution time
MinDuration time.Duration // Minimum execution time
MaxDuration time.Duration // Maximum execution time
AvgDuration time.Duration // Average execution time
LastExecuted time.Time // When the query was last executed
}
QueryMetrics stores performance metrics for a database query
type QueryRecord ¶ added in v1.4.0
type QueryRecord struct {
Query string `json:"query"`
Params []interface{} `json:"params"`
Duration time.Duration `json:"duration"`
StartTime time.Time `json:"startTime"`
Error string `json:"error,omitempty"`
Optimized bool `json:"optimized"`
Suggestion string `json:"suggestion,omitempty"`
}
QueryRecord stores information about a query execution
type QueryWithArgs ¶ added in v1.9.0
type QueryWithArgs struct {
Query string
Args []interface{}
}
QueryWithArgs represents a query with its arguments
type SQLIssueDetector ¶ added in v1.4.0
type SQLIssueDetector struct {
// contains filtered or unexported fields
}
SQLIssueDetector detects potential issues in SQL queries
func NewSQLIssueDetector ¶ added in v1.4.0
func NewSQLIssueDetector() *SQLIssueDetector
NewSQLIssueDetector creates a new SQL issue detector
func (*SQLIssueDetector) AddPattern ¶ added in v1.4.0
func (d *SQLIssueDetector) AddPattern(name, pattern string)
AddPattern adds a pattern for detecting SQL issues
func (*SQLIssueDetector) DetectIssues ¶ added in v1.4.0
func (d *SQLIssueDetector) DetectIssues(query string) map[string]string
DetectIssues detects issues in a SQL query
type SQLiteStrategy ¶ added in v1.9.0
type SQLiteStrategy struct{}
SQLiteStrategy implements DatabaseStrategy for SQLite
func (*SQLiteStrategy) GetColumnsQueries ¶ added in v1.9.0
func (s *SQLiteStrategy) GetColumnsQueries(table string) []QueryWithArgs
GetColumnsQueries returns queries for retrieving columns in SQLite
func (*SQLiteStrategy) GetRelationshipsQueries ¶ added in v1.9.0
func (s *SQLiteStrategy) GetRelationshipsQueries(table string) []QueryWithArgs
GetRelationshipsQueries returns queries for retrieving relationships in SQLite
func (*SQLiteStrategy) GetTablesQueries ¶ added in v1.9.0
func (s *SQLiteStrategy) GetTablesQueries() []QueryWithArgs
GetTablesQueries returns queries for retrieving tables in SQLite