database

package
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 28, 2025 License: GPL-3.0 Imports: 9 Imported by: 0

Documentation

Overview

Package database provides a unified interface for interacting with MySQL and PostgreSQL databases.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ColumnInfo

type ColumnInfo struct {
	Name            string  `json:"name"`                 // Column name
	Type            string  `json:"type"`                 // Data type (e.g., "VARCHAR", "INT")
	IsNullable      bool    `json:"is_nullable"`          // Whether the column allows NULL values
	DefaultValue    *string `json:"default_value"`        // Default value for the column, if any
	IsPrimaryKey    bool    `json:"is_primary_key"`       // Whether this column is part of the primary key
	IsAutoIncrement bool    `json:"is_auto_increment"`    // Whether this column auto-increments
	MaxLength       *int    `json:"max_length,omitempty"` // Maximum length for string types
}

ColumnInfo represents detailed information about a database table column.

type Database

type Database interface {
	// Connect establishes a connection to the database using the provided context.
	// It returns an error if the connection cannot be established.
	Connect(ctx context.Context) error

	// Close closes the database connection and releases associated resources.
	// It returns an error if the connection cannot be closed properly.
	Close() error

	// Ping verifies the database connection is still alive and accessible.
	// It returns an error if the database is unreachable.
	Ping(ctx context.Context) error

	// Query executes a SQL query that returns rows, typically a SELECT statement.
	// It accepts a query string and optional arguments for parameter binding.
	Query(ctx context.Context, query string, args ...any) (*sql.Rows, error)

	// QueryRow executes a SQL query that is expected to return at most one row.
	// It accepts a query string and optional arguments for parameter binding.
	QueryRow(ctx context.Context, query string, args ...any) *sql.Row

	// Exec executes a SQL statement that doesn't return rows, such as INSERT, UPDATE, or DELETE.
	// It returns a Result containing information about the execution.
	Exec(ctx context.Context, query string, args ...any) (sql.Result, error)

	// ListTables returns a list of all table names in the current database.
	ListTables(ctx context.Context) ([]string, error)

	// ListDatabases returns a list of all available database names on the server.
	ListDatabases(ctx context.Context) ([]string, error)

	// DescribeTable returns detailed schema information about the specified table,
	// including column definitions, indexes, and metadata.
	DescribeTable(ctx context.Context, tableName string) (*TableSchema, error)

	// GetTableData retrieves data from the specified table with pagination support.
	// The limit parameter controls how many rows to return, and offset specifies how many rows to skip.
	GetTableData(ctx context.Context, tableName string, limit int, offset int) (*TableData, error)

	// ExplainQuery returns the execution plan for the given SQL query in JSON format.
	ExplainQuery(ctx context.Context, query string) (string, error)

	// GetDB returns the underlying *sql.DB instance for direct database operations.
	GetDB() *sql.DB

	// GetDriverName returns the name of the database driver (e.g., "mysql", "postgres").
	GetDriverName() string
}

Database defines the interface for database operations that must be implemented by all database drivers. It provides a unified API for connecting to, querying, and inspecting database schemas.

type IndexInfo

type IndexInfo struct {
	Name      string   `json:"name"`       // Index name
	Columns   []string `json:"columns"`    // List of columns that make up the index
	IsUnique  bool     `json:"is_unique"`  // Whether the index enforces uniqueness
	IsPrimary bool     `json:"is_primary"` // Whether this is the primary key index
}

IndexInfo represents information about a database table index.

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager handles database connections and provides a factory for creating database instances. It supports both MySQL and PostgreSQL databases with connection pooling and SSL configuration.

func NewManager

func NewManager(cfg config.DatabaseConfig) (*Manager, error)

NewManager creates a new database manager with the given configuration. It validates the configuration but does not establish a connection until Connect is called. Returns an error if the configuration is invalid.

func (*Manager) Close

func (m *Manager) Close() error

Close closes the database connection and releases associated resources. It's safe to call even if no connection has been established.

func (*Manager) Connect

func (m *Manager) Connect(ctx context.Context) error

Connect establishes a connection to the database based on the configured database type. It creates the appropriate database instance (MySQL or PostgreSQL) and connects to it. Returns an error if the database type is unsupported or if the connection fails.

func (*Manager) GetDatabase

func (m *Manager) GetDatabase() Database

GetDatabase returns the active database connection instance. Returns nil if no connection has been established yet.

func (*Manager) Ping

func (m *Manager) Ping(ctx context.Context) error

Ping verifies the database connection is still alive and accessible. Returns an error if no connection has been established or if the database is unreachable.

type MySQL

type MySQL struct {
	// contains filtered or unexported fields
}

MySQL implements the Database interface for MySQL database connections. It provides MySQL-specific implementations of database operations including schema introspection, data access, and query execution with SSL support.

func NewMySQL

func NewMySQL(cfg config.DatabaseConfig) (*MySQL, error)

NewMySQL creates a new MySQL database instance with the given configuration. The connection is not established until Connect() is called.

func (*MySQL) Close

func (m *MySQL) Close() error

Close closes the MySQL database connection and releases associated resources. It's safe to call even if no connection has been established.

func (*MySQL) Connect

func (m *MySQL) Connect(ctx context.Context) error

Connect establishes a connection to the MySQL database. It builds the DSN from configuration, opens the connection, configures the connection pool, and verifies connectivity with a ping. Returns an error if any step fails.

func (*MySQL) DescribeTable

func (m *MySQL) DescribeTable(ctx context.Context, tableName string) (*TableSchema, error)

DescribeTable returns detailed schema information about the specified MySQL table. It retrieves column definitions, data types, constraints, and index information using the INFORMATION_SCHEMA tables.

func (*MySQL) Exec

func (m *MySQL) Exec(ctx context.Context, query string, args ...any) (sql.Result, error)

Exec executes a SQL statement that doesn't return rows, such as INSERT, UPDATE, or DELETE. It supports parameter binding to prevent SQL injection attacks. Returns a Result containing information about the execution.

func (*MySQL) ExplainQuery

func (m *MySQL) ExplainQuery(ctx context.Context, query string) (string, error)

ExplainQuery returns the execution plan for the given SQL query in JSON format. Uses MySQL's EXPLAIN FORMAT=JSON command to provide detailed query analysis.

func (*MySQL) GetDB

func (m *MySQL) GetDB() *sql.DB

GetDB returns the underlying *sql.DB instance for direct database operations. Returns nil if no connection has been established.

func (*MySQL) GetDriverName

func (m *MySQL) GetDriverName() string

GetDriverName returns the name of the database driver. Always returns "mysql" for MySQL connections.

func (*MySQL) GetTableData

func (m *MySQL) GetTableData(ctx context.Context, tableName string, limit int, offset int) (*TableData, error)

GetTableData retrieves data from the specified MySQL table with pagination support. If limit is 0 or negative, it defaults to 100 rows. The method also returns the total row count for pagination purposes.

func (*MySQL) ListDatabases

func (m *MySQL) ListDatabases(ctx context.Context) ([]string, error)

ListDatabases returns a list of all available database names on the MySQL server. Uses the SHOW DATABASES command to retrieve database names.

func (*MySQL) ListTables

func (m *MySQL) ListTables(ctx context.Context) ([]string, error)

ListTables returns a list of all table names in the current MySQL database. Uses the SHOW TABLES command to retrieve table names.

func (*MySQL) Ping

func (m *MySQL) Ping(ctx context.Context) error

Ping verifies that the MySQL database connection is still alive and accessible. Returns an error if no connection exists or if the database is unreachable.

func (*MySQL) Query

func (m *MySQL) Query(ctx context.Context, query string, args ...any) (*sql.Rows, error)

Query executes a SQL query that returns rows, typically a SELECT statement. It supports parameter binding to prevent SQL injection attacks.

func (*MySQL) QueryRow

func (m *MySQL) QueryRow(ctx context.Context, query string, args ...any) *sql.Row

QueryRow executes a SQL query that is expected to return at most one row. It supports parameter binding to prevent SQL injection attacks.

type PostgreSQL

type PostgreSQL struct {
	// contains filtered or unexported fields
}

PostgreSQL implements the Database interface for PostgreSQL database connections. It provides PostgreSQL-specific implementations of database operations including schema introspection, data access, and query execution with SSL support.

func NewPostgreSQL

func NewPostgreSQL(cfg config.DatabaseConfig) (*PostgreSQL, error)

NewPostgreSQL creates a new PostgreSQL database instance with the given configuration. The connection is not established until Connect() is called.

func (*PostgreSQL) Close

func (p *PostgreSQL) Close() error

Close closes the PostgreSQL database connection and releases associated resources. It's safe to call even if no connection has been established.

func (*PostgreSQL) Connect

func (p *PostgreSQL) Connect(ctx context.Context) error

Connect establishes a connection to the PostgreSQL database. It builds the DSN from configuration, opens the connection, configures the connection pool, and verifies connectivity with a ping. Returns an error if any step fails.

func (*PostgreSQL) DescribeTable

func (p *PostgreSQL) DescribeTable(ctx context.Context, tableName string) (*TableSchema, error)

DescribeTable returns detailed schema information about the specified PostgreSQL table. It retrieves column definitions, data types, constraints, and index information using the information_schema views and system catalogs.

func (*PostgreSQL) Exec

func (p *PostgreSQL) Exec(ctx context.Context, query string, args ...any) (sql.Result, error)

Exec executes a SQL statement that doesn't return rows, such as INSERT, UPDATE, or DELETE. It supports parameter binding to prevent SQL injection attacks. Returns a Result containing information about the execution.

func (*PostgreSQL) ExplainQuery

func (p *PostgreSQL) ExplainQuery(ctx context.Context, query string) (string, error)

ExplainQuery returns the execution plan for the given SQL query in JSON format. Uses PostgreSQL's EXPLAIN (FORMAT JSON) command to provide detailed query analysis.

func (*PostgreSQL) GetDB

func (p *PostgreSQL) GetDB() *sql.DB

GetDB returns the underlying *sql.DB instance for direct database operations. Returns nil if no connection has been established.

func (*PostgreSQL) GetDriverName

func (p *PostgreSQL) GetDriverName() string

GetDriverName returns the name of the database driver. Always returns "postgres" for PostgreSQL connections.

func (*PostgreSQL) GetTableData

func (p *PostgreSQL) GetTableData(ctx context.Context, tableName string, limit int, offset int) (*TableData, error)

GetTableData retrieves data from the specified PostgreSQL table with pagination support. If limit is 0 or negative, it defaults to 100 rows. The method also returns the total row count for pagination purposes.

func (*PostgreSQL) ListDatabases

func (p *PostgreSQL) ListDatabases(ctx context.Context) ([]string, error)

ListDatabases returns a list of all available database names on the PostgreSQL server. Queries the pg_database system catalog, excluding template databases.

func (*PostgreSQL) ListTables

func (p *PostgreSQL) ListTables(ctx context.Context) ([]string, error)

ListTables returns a list of all table names in the current PostgreSQL database. Queries the information_schema.tables view for tables in the 'public' schema.

func (*PostgreSQL) Ping

func (p *PostgreSQL) Ping(ctx context.Context) error

Ping verifies that the PostgreSQL database connection is still alive and accessible. Returns an error if no connection exists or if the database is unreachable.

func (*PostgreSQL) Query

func (p *PostgreSQL) Query(ctx context.Context, query string, args ...any) (*sql.Rows, error)

Query executes a SQL query that returns rows, typically a SELECT statement. It supports parameter binding to prevent SQL injection attacks.

func (*PostgreSQL) QueryRow

func (p *PostgreSQL) QueryRow(ctx context.Context, query string, args ...any) *sql.Row

QueryRow executes a SQL query that is expected to return at most one row. It supports parameter binding to prevent SQL injection attacks.

type TableData

type TableData struct {
	TableName string           `json:"table_name"` // Name of the table
	Columns   []string         `json:"columns"`    // Column names in the result set
	Rows      []map[string]any `json:"rows"`       // Actual row data as key-value pairs
	Total     int              `json:"total"`      // Total number of rows in the table
	Limit     int              `json:"limit"`      // Number of rows returned in this batch
	Offset    int              `json:"offset"`     // Number of rows skipped from the beginning
}

TableData represents paginated data from a database table.

type TableSchema

type TableSchema struct {
	TableName string         `json:"table_name"`         // Name of the table
	Columns   []ColumnInfo   `json:"columns"`            // List of column definitions
	Indexes   []IndexInfo    `json:"indexes,omitempty"`  // List of indexes on the table
	Metadata  map[string]any `json:"metadata,omitempty"` // Additional metadata about the table
}

TableSchema represents the complete schema definition of a database table.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL