Documentation
¶
Overview ¶
Package database provides database connection and adapter management.
Index ¶
- Variables
- func CheckStackedQuery(query string) error
- func CloseTestDB()
- func CollectRows[T any](rows *sql.Rows, scanFn func(rows *sql.Rows) (T, error)) ([]T, error)
- func CollectStrings(rows *sql.Rows) ([]string, error)
- func ConvertPlaceholders(query string) string
- func ConvertQuery(query string) string
- func ConvertUpsert(query string, conflictCols ...string) string
- func Env(key string) string
- func GetDB() (*sql.DB, error)
- func GetDBDriver() string
- func InitTestDB() error
- func IsConnectionError(err error) bool
- func IsMySQL() bool
- func IsPostgreSQL() bool
- func IsSQLQuery(s string) bool
- func IsTestDBOverride() bool
- func QualifiedTicketTypeColumn(alias string) string
- func ResetDB()
- func RunMigrations(db *sql.DB) (int, error)
- func SetDB(db *sql.DB)
- func TicketTypeColumn() string
- type ColumnDefinition
- type ColumnInfo
- type ConstraintDefinition
- type DBAdapter
- type DatabaseConfig
- type DatabaseFactory
- type DatabaseFeatures
- type DatabaseType
- type IDatabase
- type IDatabaseFactory
- type ITransaction
- type IndexDefinition
- type MySQLAdapter
- func (m *MySQLAdapter) CaseInsensitiveLike(column, pattern string) string
- func (m *MySQLAdapter) Exec(db *sql.DB, query string, args ...interface{}) (sql.Result, error)
- func (m *MySQLAdapter) ExecTx(tx *sql.Tx, query string, args ...interface{}) (sql.Result, error)
- func (m *MySQLAdapter) InsertWithReturning(db *sql.DB, query string, args ...interface{}) (int64, error)
- func (m *MySQLAdapter) InsertWithReturningTx(tx *sql.Tx, query string, args ...interface{}) (int64, error)
- func (m *MySQLAdapter) IntervalAdd(timestamp string, amount int, unit string) string
- func (m *MySQLAdapter) Query(db *sql.DB, query string, args ...interface{}) (*sql.Rows, error)
- func (m *MySQLAdapter) QueryRow(db *sql.DB, query string, args ...interface{}) *sql.Row
- func (m *MySQLAdapter) QueryRowTx(tx *sql.Tx, query string, args ...interface{}) *sql.Row
- func (m *MySQLAdapter) QueryTx(tx *sql.Tx, query string, args ...interface{}) (*sql.Rows, error)
- func (m *MySQLAdapter) TypeCast(value, targetType string) string
- type MySQLDatabase
- func (m *MySQLDatabase) Begin(ctx context.Context) (ITransaction, error)
- func (m *MySQLDatabase) BeginTx(ctx context.Context, opts *sql.TxOptions) (ITransaction, error)
- func (m *MySQLDatabase) BuildInsert(tableName string, data map[string]interface{}) (string, []interface{})
- func (m *MySQLDatabase) BuildSelect(tableName string, columns []string, where string, orderBy string, limit int) string
- func (m *MySQLDatabase) BuildUpdate(tableName string, data map[string]interface{}, where string, ...) (string, []interface{})
- func (m *MySQLDatabase) Close() error
- func (m *MySQLDatabase) Connect() error
- func (m *MySQLDatabase) CreateIndex(ctx context.Context, tableName, indexName string, columns []string, ...) error
- func (m *MySQLDatabase) CreateTable(ctx context.Context, definition *TableDefinition) error
- func (m *MySQLDatabase) DropIndex(ctx context.Context, tableName, indexName string) error
- func (m *MySQLDatabase) DropTable(ctx context.Context, tableName string) error
- func (m *MySQLDatabase) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func (m *MySQLDatabase) GetConcatFunction(fields []string) string
- func (m *MySQLDatabase) GetConfig() DatabaseConfig
- func (m *MySQLDatabase) GetDateFunction() string
- func (m *MySQLDatabase) GetLimitClause(limit, offset int) string
- func (m *MySQLDatabase) GetTableColumns(ctx context.Context, tableName string) ([]ColumnInfo, error)
- func (m *MySQLDatabase) GetType() DatabaseType
- func (m *MySQLDatabase) IsHealthy() bool
- func (m *MySQLDatabase) Ping() error
- func (m *MySQLDatabase) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func (m *MySQLDatabase) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
- func (m *MySQLDatabase) Quote(identifier string) string
- func (m *MySQLDatabase) QuoteValue(value interface{}) string
- func (m *MySQLDatabase) Stats() sql.DBStats
- func (m *MySQLDatabase) SupportsReturning() bool
- func (m *MySQLDatabase) TableExists(ctx context.Context, tableName string) (bool, error)
- type MySQLTransaction
- func (t *MySQLTransaction) Commit() error
- func (t *MySQLTransaction) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func (t *MySQLTransaction) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func (t *MySQLTransaction) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
- func (t *MySQLTransaction) Rollback() error
- type PostgreSQLAdapter
- func (p *PostgreSQLAdapter) CaseInsensitiveLike(column, pattern string) string
- func (p *PostgreSQLAdapter) Exec(db *sql.DB, query string, args ...interface{}) (sql.Result, error)
- func (p *PostgreSQLAdapter) ExecTx(tx *sql.Tx, query string, args ...interface{}) (sql.Result, error)
- func (p *PostgreSQLAdapter) InsertWithReturning(db *sql.DB, query string, args ...interface{}) (int64, error)
- func (p *PostgreSQLAdapter) InsertWithReturningTx(tx *sql.Tx, query string, args ...interface{}) (int64, error)
- func (p *PostgreSQLAdapter) IntervalAdd(timestamp string, amount int, unit string) string
- func (p *PostgreSQLAdapter) Query(db *sql.DB, query string, args ...interface{}) (*sql.Rows, error)
- func (p *PostgreSQLAdapter) QueryRow(db *sql.DB, query string, args ...interface{}) *sql.Row
- func (p *PostgreSQLAdapter) QueryRowTx(tx *sql.Tx, query string, args ...interface{}) *sql.Row
- func (p *PostgreSQLAdapter) QueryTx(tx *sql.Tx, query string, args ...interface{}) (*sql.Rows, error)
- func (p *PostgreSQLAdapter) TypeCast(value, targetType string) string
- type PostgreSQLDatabase
- func (p *PostgreSQLDatabase) Begin(ctx context.Context) (ITransaction, error)
- func (p *PostgreSQLDatabase) BeginTx(ctx context.Context, opts *sql.TxOptions) (ITransaction, error)
- func (p *PostgreSQLDatabase) BuildInsert(tableName string, data map[string]interface{}) (string, []interface{})
- func (p *PostgreSQLDatabase) BuildSelect(tableName string, columns []string, where string, orderBy string, limit int) string
- func (p *PostgreSQLDatabase) BuildUpdate(tableName string, data map[string]interface{}, where string, ...) (string, []interface{})
- func (p *PostgreSQLDatabase) Close() error
- func (p *PostgreSQLDatabase) Connect() error
- func (p *PostgreSQLDatabase) CreateIndex(ctx context.Context, tableName, indexName string, columns []string, ...) error
- func (p *PostgreSQLDatabase) CreateTable(ctx context.Context, definition *TableDefinition) error
- func (p *PostgreSQLDatabase) DropIndex(ctx context.Context, tableName, indexName string) error
- func (p *PostgreSQLDatabase) DropTable(ctx context.Context, tableName string) error
- func (p *PostgreSQLDatabase) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func (p *PostgreSQLDatabase) GetConcatFunction(fields []string) string
- func (p *PostgreSQLDatabase) GetConfig() DatabaseConfig
- func (p *PostgreSQLDatabase) GetDateFunction() string
- func (p *PostgreSQLDatabase) GetLimitClause(limit, offset int) string
- func (p *PostgreSQLDatabase) GetTableColumns(ctx context.Context, tableName string) ([]ColumnInfo, error)
- func (p *PostgreSQLDatabase) GetType() DatabaseType
- func (p *PostgreSQLDatabase) IsHealthy() bool
- func (p *PostgreSQLDatabase) Ping() error
- func (p *PostgreSQLDatabase) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func (p *PostgreSQLDatabase) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
- func (p *PostgreSQLDatabase) Quote(identifier string) string
- func (p *PostgreSQLDatabase) QuoteValue(value interface{}) string
- func (p *PostgreSQLDatabase) Stats() sql.DBStats
- func (p *PostgreSQLDatabase) SupportsReturning() bool
- func (p *PostgreSQLDatabase) TableExists(ctx context.Context, tableName string) (bool, error)
- type PostgreSQLTransaction
- func (t *PostgreSQLTransaction) Commit() error
- func (t *PostgreSQLTransaction) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func (t *PostgreSQLTransaction) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func (t *PostgreSQLTransaction) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
- func (t *PostgreSQLTransaction) Rollback() error
- type QueryBuilder
- func (qb *QueryBuilder) DB() *sqlx.DB
- func (qb *QueryBuilder) Exec(query string, args ...interface{}) (sql.Result, error)
- func (qb *QueryBuilder) In(query string, args ...interface{}) (string, []interface{}, error)
- func (qb *QueryBuilder) NewSelect(columns ...string) *SelectBuilder
- func (qb *QueryBuilder) Query(query string, args ...interface{}) (*sql.Rows, error)
- func (qb *QueryBuilder) QueryRow(query string, args ...interface{}) *sql.Row
- func (qb *QueryBuilder) Rebind(query string) string
- type SchemaConverter
- type SelectBuilder
- func (sb *SelectBuilder) From(table string) *SelectBuilder
- func (sb *SelectBuilder) LeftJoin(join string) *SelectBuilder
- func (sb *SelectBuilder) Limit(limit int) *SelectBuilder
- func (sb *SelectBuilder) Offset(offset int) *SelectBuilder
- func (sb *SelectBuilder) OrderBy(columns ...string) *SelectBuilder
- func (sb *SelectBuilder) ToSQL() (string, []interface{}, error)
- func (sb *SelectBuilder) Where(condition string, args ...interface{}) *SelectBuilder
- type TableDefinition
- type XMLColumn
- type XMLForeignKey
- type XMLIndex
- type XMLIndexColumn
- type XMLSchema
- type XMLTable
Constants ¶
This section is empty.
Variables ¶
var ErrDatabaseNotImplemented = errors.New("database type not implemented")
ErrDatabaseNotImplemented is returned for database types that are declared (Oracle, SQLServer) but have no driver yet. Test for it with errors.Is.
Functions ¶
func CheckStackedQuery ¶
CheckStackedQuery returns an error if the query contains more than one statement separated by ';' outside of a string literal — the most common SQL injection pattern (e.g. "SELECT ... ; DROP TABLE users").
The scan tracks single-quote state so ';' inside string literals (such as 'O”Brien' or a quoted semicolon in a value) does not trigger a false positive. A query that ends with a single trailing ';' (a common style) is accepted; only an interior ';' that would start a second statement is flagged.
func CloseTestDB ¶
func CloseTestDB()
CloseTestDB is a no-op to avoid interfering with the global service-managed database connection. Left for API compatibility.
func CollectRows ¶
CollectRows is a generic helper that collects rows into a slice. The scanFn should scan a single row and return the value.
Usage:
users, err := database.CollectRows(rows, func(rows *sql.Rows) (*User, error) {
var u User
err := rows.Scan(&u.ID, &u.Name, &u.Email)
return &u, err
})
func CollectStrings ¶
CollectStrings scans rows containing a single string column. This is a common pattern for queries like "SELECT name FROM table".
func ConvertPlaceholders ¶
ConvertPlaceholders converts SQL placeholders to the format required by the current database. This is the ONLY function that should be used for placeholder conversion in the codebase. Do NOT use qb.Rebind() directly - always go through this function.
IMPORTANT: Only ? placeholders are allowed. Using $N placeholders will panic. - For PostgreSQL: ? → $1, $2, ... - For MySQL: ? passed through as-is
Example:
query := database.ConvertPlaceholders("SELECT * FROM users WHERE id = ? AND name = ?")
rows, err := db.Query(query, id, name)
func ConvertQuery ¶
This extends the existing ConvertPlaceholders functionality.
func ConvertUpsert ¶ added in v0.10.0
ConvertUpsert converts a MySQL-dialect upsert for the active driver and then applies ConvertPlaceholders. Write the query the MySQL way, either
INSERT INTO t (a, b, c) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE c = VALUES(c), d = ? REPLACE INTO t (a, b, c) VALUES (?, ?, ?)
and name the unique key that decides a conflict in conflictCols. MySQL gets the query unchanged. PostgreSQL needs that key spelled out, so it gets ON CONFLICT (conflictCols) DO UPDATE SET …, with VALUES(col) rewritten to EXCLUDED.col; REPLACE INTO updates every non-key column. Placeholder order is preserved.
func GetDB ¶
GetDB returns the database connection singleton from the service registry. Service registry is the single source of truth for database connections.
func GetDBDriver ¶
func GetDBDriver() string
GetDBDriver returns the active, normalized database driver ("postgres" for any PostgreSQL alias); see dbconfig.Driver.
func InitTestDB ¶
func InitTestDB() error
InitTestDB initializes a database connection for tests using the project service adapter. It is safe to call multiple times. It does not create schema by default; individual tests should create required tables with CREATE TABLE IF NOT EXISTS as needed.
func IsConnectionError ¶
IsConnectionError reports whether the provided error indicates the database connection is unavailable. It is intentionally broad so handlers can return a 503 response instead of treating these failures as bad requests.
func IsSQLQuery ¶
IsSQLQuery returns true if the string looks like a SQL query — i.e. its first non-whitespace token is a SQL DML/DDL keyword. Used by the gk-lint sql-sprintf rule to decide whether a fmt.Sprintf format string warrants inspection, and safe to call on arbitrary input.
func IsTestDBOverride ¶
func IsTestDBOverride() bool
IsTestDBOverride reports whether a test database has been explicitly injected via SetDB.
func QualifiedTicketTypeColumn ¶
QualifiedTicketTypeColumn returns the column name prefixed with the provided alias.
func ResetDB ¶
func ResetDB()
ResetDB restores the test-injected DB to the previously saved value. This allows tests that inject mocks to not interfere with other tests that expect the real test database to be available.
func RunMigrations ¶
RunMigrations runs database migrations using the migrate CLI tool. Returns the number of migrations applied and any error encountered.
func SetDB ¶
SetDB allows tests to inject a mock *sql.DB for functions that call GetDB. Use ResetDB to restore the previous value. Uses a stack to handle nested calls.
func TicketTypeColumn ¶
func TicketTypeColumn() string
TicketTypeColumn returns the ticket type column name for the active driver.
Types ¶
type ColumnDefinition ¶
type ColumnDefinition struct {
Name string
DataType string
Size *int
Precision *int
Scale *int
NotNull bool
PrimaryKey bool
AutoIncrement bool
DefaultValue *string
}
ColumnDefinition defines a table column.
type ColumnInfo ¶
type ColumnInfo struct {
Name string
DataType string
IsNullable bool
DefaultValue *string
MaxLength *int
IsPrimaryKey bool
IsAutoIncrement bool
}
ColumnInfo represents database column information.
type ConstraintDefinition ¶
type ConstraintDefinition struct {
Name string
Type string // PRIMARY_KEY, FOREIGN_KEY, UNIQUE, CHECK
Columns []string
ReferenceTable *string
ReferenceColumns []string
OnDelete *string // CASCADE, SET NULL, RESTRICT
OnUpdate *string // CASCADE, SET NULL, RESTRICT
}
ConstraintDefinition defines a table constraint.
type DBAdapter ¶
type DBAdapter interface {
// InsertWithReturning handles INSERT ... RETURNING for different databases.
// Accepts PostgreSQL-style queries with $N placeholders (handles repeated placeholders).
InsertWithReturning(db *sql.DB, query string, args ...interface{}) (int64, error)
// InsertWithReturningTx handles INSERT ... RETURNING within a transaction.
// Accepts PostgreSQL-style queries with $N placeholders (handles repeated placeholders).
InsertWithReturningTx(tx *sql.Tx, query string, args ...interface{}) (int64, error)
// Exec executes a query with PostgreSQL-style $N placeholders.
// Handles repeated placeholders and placeholder conversion for MySQL.
Exec(db *sql.DB, query string, args ...interface{}) (sql.Result, error)
// ExecTx executes a query within a transaction with PostgreSQL-style $N placeholders.
// Handles repeated placeholders and placeholder conversion for MySQL.
ExecTx(tx *sql.Tx, query string, args ...interface{}) (sql.Result, error)
// Query executes a query with PostgreSQL-style $N placeholders and returns rows.
// Handles repeated placeholders and placeholder conversion for MySQL.
Query(db *sql.DB, query string, args ...interface{}) (*sql.Rows, error)
// QueryTx executes a query within a transaction and returns rows.
// Handles repeated placeholders and placeholder conversion for MySQL.
QueryTx(tx *sql.Tx, query string, args ...interface{}) (*sql.Rows, error)
// QueryRow executes a query expected to return at most one row.
// Handles repeated placeholders and placeholder conversion for MySQL.
QueryRow(db *sql.DB, query string, args ...interface{}) *sql.Row
// QueryRowTx executes a query within a transaction expected to return at most one row.
// Handles repeated placeholders and placeholder conversion for MySQL.
QueryRowTx(tx *sql.Tx, query string, args ...interface{}) *sql.Row
// CaseInsensitiveLike returns the appropriate case-insensitive LIKE operator
CaseInsensitiveLike(column, pattern string) string
// TypeCast handles type casting for different databases
TypeCast(value, targetType string) string
// IntervalAdd returns SQL expression for adding an interval to a timestamp.
// unit: "SECOND", "MINUTE", "HOUR", "DAY"
// Example: IntervalAdd("NOW()", 1, "MINUTE") returns database-specific SQL
IntervalAdd(timestamp string, amount int, unit string) string
}
DBAdapter provides database-specific query adaptations.
func GetAdapter ¶
func GetAdapter() DBAdapter
GetAdapter returns the appropriate database adapter based on configuration.
type DatabaseConfig ¶
type DatabaseConfig struct {
Type DatabaseType `json:"type" yaml:"type"`
Host string `json:"host" yaml:"host"`
Port string `json:"port" yaml:"port"`
Database string `json:"database" yaml:"database"`
Username string `json:"username" yaml:"username"`
Password string `json:"password" yaml:"password"`
SSLMode string `json:"ssl_mode" yaml:"ssl_mode"`
// Connection pool settings
MaxOpenConns int `json:"max_open_conns" yaml:"max_open_conns"`
MaxIdleConns int `json:"max_idle_conns" yaml:"max_idle_conns"`
ConnMaxLifetime time.Duration `json:"conn_max_lifetime" yaml:"conn_max_lifetime"`
ConnMaxIdleTime time.Duration `json:"conn_max_idle_time" yaml:"conn_max_idle_time"`
// Database-specific options
Options map[string]string `json:"options,omitempty" yaml:"options,omitempty"`
}
DatabaseConfig holds database connection configuration.
type DatabaseFactory ¶
type DatabaseFactory struct{}
DatabaseFactory implements IDatabaseFactory.
func (*DatabaseFactory) Create ¶
func (f *DatabaseFactory) Create(config DatabaseConfig) (IDatabase, error)
Create creates a database instance based on the configuration.
func (*DatabaseFactory) GetSupportedTypes ¶
func (f *DatabaseFactory) GetSupportedTypes() []DatabaseType
GetSupportedTypes returns the database types with a working implementation.
func (*DatabaseFactory) ValidateConfig ¶
func (f *DatabaseFactory) ValidateConfig(config DatabaseConfig) error
ValidateConfig validates the database configuration.
type DatabaseFeatures ¶
type DatabaseFeatures struct {
SupportsReturning bool
SupportsUpsert bool
SupportsJSONColumn bool
SupportsArrayColumn bool
SupportsWindowFunctions bool
SupportsCTE bool // Common Table Expressions
MaxIdentifierLength int
MaxIndexNameLength int
}
DatabaseFeatures represents database-specific feature support.
func GetDatabaseFeatures ¶
func GetDatabaseFeatures(dbType DatabaseType) DatabaseFeatures
GetDatabaseFeatures returns the features supported by a database type.
type DatabaseType ¶
type DatabaseType string
DatabaseType represents the supported database backends.
const ( PostgreSQL DatabaseType = "postgresql" MySQL DatabaseType = "mysql" Oracle DatabaseType = "oracle" SQLServer DatabaseType = "sqlserver" )
type IDatabase ¶
type IDatabase interface {
// Connection management
Connect() error
Close() error
Ping() error
GetType() DatabaseType
GetConfig() DatabaseConfig
// Query operations
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)
// Transaction support
Begin(ctx context.Context) (ITransaction, error)
BeginTx(ctx context.Context, opts *sql.TxOptions) (ITransaction, error)
// Schema operations
TableExists(ctx context.Context, tableName string) (bool, error)
GetTableColumns(ctx context.Context, tableName string) ([]ColumnInfo, error)
CreateTable(ctx context.Context, definition *TableDefinition) error
DropTable(ctx context.Context, tableName string) error
// Index operations
CreateIndex(ctx context.Context, tableName, indexName string, columns []string, unique bool) error
DropIndex(ctx context.Context, tableName, indexName string) error
// Utility methods
Quote(identifier string) string
QuoteValue(value interface{}) string
BuildInsert(tableName string, data map[string]interface{}) (string, []interface{})
BuildUpdate(tableName string, data map[string]interface{}, where string, whereArgs []interface{}) (string, []interface{})
BuildSelect(tableName string, columns []string, where string, orderBy string, limit int) string
// Database-specific SQL generation
GetLimitClause(limit, offset int) string
GetDateFunction() string
GetConcatFunction(fields []string) string
SupportsReturning() bool
// Health and monitoring
Stats() sql.DBStats
IsHealthy() bool
}
IDatabase defines the database abstraction interface (inspired by OTRS Kernel::System::DB).
type IDatabaseFactory ¶
type IDatabaseFactory interface {
Create(config DatabaseConfig) (IDatabase, error)
GetSupportedTypes() []DatabaseType
ValidateConfig(config DatabaseConfig) error
}
IDatabaseFactory creates database instances.
func NewDatabaseFactory ¶
func NewDatabaseFactory() IDatabaseFactory
NewDatabaseFactory creates a new database factory instance.
type ITransaction ¶
type ITransaction 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)
Commit() error
Rollback() error
}
ITransaction defines the transaction interface.
type IndexDefinition ¶
type IndexDefinition struct {
Name string
Columns []string
Unique bool
Type string // btree, hash, gin, gist for PostgreSQL
}
IndexDefinition defines a table index.
type MySQLAdapter ¶
type MySQLAdapter struct{}
MySQLAdapter implements DBAdapter for MySQL/MariaDB.
func (*MySQLAdapter) CaseInsensitiveLike ¶
func (m *MySQLAdapter) CaseInsensitiveLike(column, pattern string) string
func (*MySQLAdapter) InsertWithReturning ¶
func (*MySQLAdapter) InsertWithReturningTx ¶
func (*MySQLAdapter) IntervalAdd ¶
func (m *MySQLAdapter) IntervalAdd(timestamp string, amount int, unit string) string
func (*MySQLAdapter) QueryRowTx ¶
func (*MySQLAdapter) TypeCast ¶
func (m *MySQLAdapter) TypeCast(value, targetType string) string
type MySQLDatabase ¶
type MySQLDatabase struct {
// contains filtered or unexported fields
}
MySQLDatabase implements IDatabase for MySQL/MariaDB.
func NewMySQLDatabase ¶
func NewMySQLDatabase(config DatabaseConfig) *MySQLDatabase
NewMySQLDatabase creates a new MySQL database instance.
func (*MySQLDatabase) Begin ¶
func (m *MySQLDatabase) Begin(ctx context.Context) (ITransaction, error)
Begin starts a transaction.
func (*MySQLDatabase) BeginTx ¶
func (m *MySQLDatabase) BeginTx(ctx context.Context, opts *sql.TxOptions) (ITransaction, error)
BeginTx starts a transaction with options.
func (*MySQLDatabase) BuildInsert ¶
func (m *MySQLDatabase) BuildInsert(tableName string, data map[string]interface{}) (string, []interface{})
BuildInsert builds an INSERT statement (stub implementation).
func (*MySQLDatabase) BuildSelect ¶
func (m *MySQLDatabase) BuildSelect(tableName string, columns []string, where string, orderBy string, limit int) string
BuildSelect builds a SELECT statement.
func (*MySQLDatabase) BuildUpdate ¶
func (m *MySQLDatabase) BuildUpdate(tableName string, data map[string]interface{}, where string, whereArgs []interface{}) (string, []interface{})
BuildUpdate builds an UPDATE statement (stub implementation).
func (*MySQLDatabase) Close ¶
func (m *MySQLDatabase) Close() error
Close closes the database connection.
func (*MySQLDatabase) Connect ¶
func (m *MySQLDatabase) Connect() error
Connect establishes connection to MySQL database.
func (*MySQLDatabase) CreateIndex ¶
func (m *MySQLDatabase) CreateIndex(ctx context.Context, tableName, indexName string, columns []string, unique bool) error
CreateIndex creates an index.
func (*MySQLDatabase) CreateTable ¶
func (m *MySQLDatabase) CreateTable(ctx context.Context, definition *TableDefinition) error
CreateTable creates a table from definition (stub implementation).
func (*MySQLDatabase) DropIndex ¶
func (m *MySQLDatabase) DropIndex(ctx context.Context, tableName, indexName string) error
DropIndex drops an index.
func (*MySQLDatabase) DropTable ¶
func (m *MySQLDatabase) DropTable(ctx context.Context, tableName string) error
DropTable drops a table.
func (*MySQLDatabase) Exec ¶
func (m *MySQLDatabase) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
Exec executes a query and returns the result.
func (*MySQLDatabase) GetConcatFunction ¶
func (m *MySQLDatabase) GetConcatFunction(fields []string) string
GetConcatFunction returns concatenation function.
func (*MySQLDatabase) GetConfig ¶
func (m *MySQLDatabase) GetConfig() DatabaseConfig
GetConfig returns the database configuration.
func (*MySQLDatabase) GetDateFunction ¶
func (m *MySQLDatabase) GetDateFunction() string
GetDateFunction returns current date function.
func (*MySQLDatabase) GetLimitClause ¶
func (m *MySQLDatabase) GetLimitClause(limit, offset int) string
GetLimitClause returns MySQL-specific LIMIT clause.
func (*MySQLDatabase) GetTableColumns ¶
func (m *MySQLDatabase) GetTableColumns(ctx context.Context, tableName string) ([]ColumnInfo, error)
GetTableColumns returns column information for a table (stub implementation).
func (*MySQLDatabase) GetType ¶
func (m *MySQLDatabase) GetType() DatabaseType
GetType returns the database type.
func (*MySQLDatabase) IsHealthy ¶
func (m *MySQLDatabase) IsHealthy() bool
IsHealthy checks if database is healthy.
func (*MySQLDatabase) Ping ¶
func (m *MySQLDatabase) Ping() error
Ping tests the database connection.
func (*MySQLDatabase) Query ¶
func (m *MySQLDatabase) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
Query executes a query and returns rows.
func (*MySQLDatabase) Quote ¶
func (m *MySQLDatabase) Quote(identifier string) string
Quote quotes an identifier (MySQL uses backticks).
func (*MySQLDatabase) QuoteValue ¶
func (m *MySQLDatabase) QuoteValue(value interface{}) string
QuoteValue quotes a value.
func (*MySQLDatabase) Stats ¶
func (m *MySQLDatabase) Stats() sql.DBStats
Stats returns database connection statistics.
func (*MySQLDatabase) SupportsReturning ¶
func (m *MySQLDatabase) SupportsReturning() bool
SupportsReturning returns false for MySQL.
func (*MySQLDatabase) TableExists ¶
TableExists checks if a table exists.
type MySQLTransaction ¶
type MySQLTransaction struct {
// contains filtered or unexported fields
}
MySQLTransaction implements ITransaction for MySQL.
func (*MySQLTransaction) Commit ¶
func (t *MySQLTransaction) Commit() error
func (*MySQLTransaction) Rollback ¶
func (t *MySQLTransaction) Rollback() error
type PostgreSQLAdapter ¶
type PostgreSQLAdapter struct{}
PostgreSQLAdapter implements DBAdapter for PostgreSQL.
func (*PostgreSQLAdapter) CaseInsensitiveLike ¶
func (p *PostgreSQLAdapter) CaseInsensitiveLike(column, pattern string) string
func (*PostgreSQLAdapter) InsertWithReturning ¶
func (*PostgreSQLAdapter) InsertWithReturningTx ¶
func (*PostgreSQLAdapter) IntervalAdd ¶
func (p *PostgreSQLAdapter) IntervalAdd(timestamp string, amount int, unit string) string
func (*PostgreSQLAdapter) QueryRowTx ¶
func (*PostgreSQLAdapter) TypeCast ¶
func (p *PostgreSQLAdapter) TypeCast(value, targetType string) string
type PostgreSQLDatabase ¶
type PostgreSQLDatabase struct {
// contains filtered or unexported fields
}
PostgreSQLDatabase implements IDatabase for PostgreSQL.
func NewPostgreSQLDatabase ¶
func NewPostgreSQLDatabase(config DatabaseConfig) *PostgreSQLDatabase
NewPostgreSQLDatabase creates a new PostgreSQL database instance.
func (*PostgreSQLDatabase) Begin ¶
func (p *PostgreSQLDatabase) Begin(ctx context.Context) (ITransaction, error)
Begin starts a transaction.
func (*PostgreSQLDatabase) BeginTx ¶
func (p *PostgreSQLDatabase) BeginTx(ctx context.Context, opts *sql.TxOptions) (ITransaction, error)
BeginTx starts a transaction with options.
func (*PostgreSQLDatabase) BuildInsert ¶
func (p *PostgreSQLDatabase) BuildInsert(tableName string, data map[string]interface{}) (string, []interface{})
BuildInsert builds an INSERT statement.
func (*PostgreSQLDatabase) BuildSelect ¶
func (p *PostgreSQLDatabase) BuildSelect(tableName string, columns []string, where string, orderBy string, limit int) string
BuildSelect builds a SELECT statement.
func (*PostgreSQLDatabase) BuildUpdate ¶
func (p *PostgreSQLDatabase) BuildUpdate(tableName string, data map[string]interface{}, where string, whereArgs []interface{}) (string, []interface{})
BuildUpdate builds an UPDATE statement.
func (*PostgreSQLDatabase) Close ¶
func (p *PostgreSQLDatabase) Close() error
Close closes the database connection.
func (*PostgreSQLDatabase) Connect ¶
func (p *PostgreSQLDatabase) Connect() error
Connect establishes connection to PostgreSQL database.
func (*PostgreSQLDatabase) CreateIndex ¶
func (p *PostgreSQLDatabase) CreateIndex(ctx context.Context, tableName, indexName string, columns []string, unique bool) error
CreateIndex creates an index.
func (*PostgreSQLDatabase) CreateTable ¶
func (p *PostgreSQLDatabase) CreateTable(ctx context.Context, definition *TableDefinition) error
CreateTable creates a table from definition.
func (*PostgreSQLDatabase) DropIndex ¶
func (p *PostgreSQLDatabase) DropIndex(ctx context.Context, tableName, indexName string) error
DropIndex drops an index.
func (*PostgreSQLDatabase) DropTable ¶
func (p *PostgreSQLDatabase) DropTable(ctx context.Context, tableName string) error
DropTable drops a table.
func (*PostgreSQLDatabase) Exec ¶
func (p *PostgreSQLDatabase) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
Exec executes a query and returns the result.
func (*PostgreSQLDatabase) GetConcatFunction ¶
func (p *PostgreSQLDatabase) GetConcatFunction(fields []string) string
GetConcatFunction returns concatenation function.
func (*PostgreSQLDatabase) GetConfig ¶
func (p *PostgreSQLDatabase) GetConfig() DatabaseConfig
GetConfig returns the database configuration.
func (*PostgreSQLDatabase) GetDateFunction ¶
func (p *PostgreSQLDatabase) GetDateFunction() string
GetDateFunction returns current date function.
func (*PostgreSQLDatabase) GetLimitClause ¶
func (p *PostgreSQLDatabase) GetLimitClause(limit, offset int) string
GetLimitClause returns database-specific LIMIT clause.
func (*PostgreSQLDatabase) GetTableColumns ¶
func (p *PostgreSQLDatabase) GetTableColumns(ctx context.Context, tableName string) ([]ColumnInfo, error)
GetTableColumns returns column information for a table.
func (*PostgreSQLDatabase) GetType ¶
func (p *PostgreSQLDatabase) GetType() DatabaseType
GetType returns the database type.
func (*PostgreSQLDatabase) IsHealthy ¶
func (p *PostgreSQLDatabase) IsHealthy() bool
IsHealthy checks if database is healthy.
func (*PostgreSQLDatabase) Ping ¶
func (p *PostgreSQLDatabase) Ping() error
Ping tests the database connection.
func (*PostgreSQLDatabase) Query ¶
func (p *PostgreSQLDatabase) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
Query executes a query and returns rows.
func (*PostgreSQLDatabase) QueryRow ¶
func (p *PostgreSQLDatabase) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
QueryRow executes a query and returns a single row.
func (*PostgreSQLDatabase) Quote ¶
func (p *PostgreSQLDatabase) Quote(identifier string) string
Quote quotes an identifier.
func (*PostgreSQLDatabase) QuoteValue ¶
func (p *PostgreSQLDatabase) QuoteValue(value interface{}) string
QuoteValue quotes a value.
func (*PostgreSQLDatabase) Stats ¶
func (p *PostgreSQLDatabase) Stats() sql.DBStats
Stats returns database connection statistics.
func (*PostgreSQLDatabase) SupportsReturning ¶
func (p *PostgreSQLDatabase) SupportsReturning() bool
SupportsReturning returns true if database supports RETURNING clause.
func (*PostgreSQLDatabase) TableExists ¶
TableExists checks if a table exists.
type PostgreSQLTransaction ¶
type PostgreSQLTransaction struct {
// contains filtered or unexported fields
}
PostgreSQLTransaction implements ITransaction for PostgreSQL.
func (*PostgreSQLTransaction) Commit ¶
func (t *PostgreSQLTransaction) Commit() error
func (*PostgreSQLTransaction) Rollback ¶
func (t *PostgreSQLTransaction) Rollback() error
type QueryBuilder ¶
type QueryBuilder struct {
// contains filtered or unexported fields
}
QueryBuilder provides a safe, sqlx-based query builder that eliminates SQL injection risks. It wraps the standard sql.DB with sqlx functionality and handles placeholder conversion.
func GetQueryBuilder ¶
func GetQueryBuilder() (*QueryBuilder, error)
GetQueryBuilder returns a QueryBuilder using the default database connection.
func NewQueryBuilder ¶
func NewQueryBuilder(db *sql.DB) (*QueryBuilder, error)
NewQueryBuilder creates a QueryBuilder from an existing *sql.DB connection.
func (*QueryBuilder) DB ¶
func (qb *QueryBuilder) DB() *sqlx.DB
DB returns the underlying sqlx.DB for advanced operations.
func (*QueryBuilder) Exec ¶
func (qb *QueryBuilder) Exec(query string, args ...interface{}) (sql.Result, error)
Exec executes a query without returning rows.
func (*QueryBuilder) In ¶
func (qb *QueryBuilder) In(query string, args ...interface{}) (string, []interface{}, error)
In expands slice arguments for IN clauses. Example: In("SELECT * FROM users WHERE id IN (?)", []int{1,2,3}). Returns: "SELECT * FROM users WHERE id IN (?, ?, ?)", [1, 2, 3].
func (*QueryBuilder) NewSelect ¶
func (qb *QueryBuilder) NewSelect(columns ...string) *SelectBuilder
NewSelect creates a new SelectBuilder.
func (*QueryBuilder) Query ¶
func (qb *QueryBuilder) Query(query string, args ...interface{}) (*sql.Rows, error)
Query executes a query returning multiple rows.
func (*QueryBuilder) QueryRow ¶
func (qb *QueryBuilder) QueryRow(query string, args ...interface{}) *sql.Row
QueryRow executes a query expecting a single row.
func (*QueryBuilder) Rebind ¶
func (qb *QueryBuilder) Rebind(query string) string
Rebind converts a query with ? placeholders for the active driver through ConvertPlaceholders, so MySQL-dialect SQL gets the same rewrites as the rest of the codebase. Already-converted ($N) queries pass through unchanged, so the output of In and ToSQL can be handed back to Query/Exec.
type SchemaConverter ¶
type SchemaConverter struct {
// contains filtered or unexported fields
}
SchemaConverter converts between different schema formats.
func NewSchemaConverter ¶
func NewSchemaConverter(db IDatabase) *SchemaConverter
NewSchemaConverter creates a new schema converter.
func (*SchemaConverter) ExportToXML ¶
func (c *SchemaConverter) ExportToXML(outputPath string) error
ExportToXML exports the current database schema to XML format.
func (*SchemaConverter) ImportFromXML ¶
func (c *SchemaConverter) ImportFromXML(xmlPath string) error
ImportFromXML creates database tables from XML schema definition.
type SelectBuilder ¶
type SelectBuilder struct {
// contains filtered or unexported fields
}
SelectBuilder provides a fluent interface for building SELECT queries safely.
func (*SelectBuilder) From ¶
func (sb *SelectBuilder) From(table string) *SelectBuilder
From sets the table to select from.
func (*SelectBuilder) LeftJoin ¶
func (sb *SelectBuilder) LeftJoin(join string) *SelectBuilder
LeftJoin adds a LEFT JOIN clause.
func (*SelectBuilder) Limit ¶
func (sb *SelectBuilder) Limit(limit int) *SelectBuilder
Limit sets the LIMIT clause.
func (*SelectBuilder) Offset ¶
func (sb *SelectBuilder) Offset(offset int) *SelectBuilder
Offset sets the OFFSET clause.
func (*SelectBuilder) OrderBy ¶
func (sb *SelectBuilder) OrderBy(columns ...string) *SelectBuilder
OrderBy adds ORDER BY columns.
func (*SelectBuilder) ToSQL ¶
func (sb *SelectBuilder) ToSQL() (string, []interface{}, error)
ToSQL builds the SQL query and returns it with arguments.
func (*SelectBuilder) Where ¶
func (sb *SelectBuilder) Where(condition string, args ...interface{}) *SelectBuilder
Where adds a WHERE condition with parameterized values.
type TableDefinition ¶
type TableDefinition struct {
Name string
Columns []ColumnDefinition
Indexes []IndexDefinition
Constraints []ConstraintDefinition
}
TableDefinition represents a database table structure.
type XMLColumn ¶
type XMLColumn struct {
XMLName xml.Name `xml:"Column"`
Name string `xml:"Name,attr"`
Type string `xml:"Type,attr"`
Size *int `xml:"Size,attr,omitempty"`
Required bool `xml:"Required,attr"`
PrimaryKey bool `xml:"PrimaryKey,attr,omitempty"`
AutoIncrement bool `xml:"AutoIncrement,attr,omitempty"`
Default *string `xml:"Default,attr,omitempty"`
}
XMLColumn represents a table column in XML format.
type XMLForeignKey ¶
type XMLForeignKey struct {
XMLName xml.Name `xml:"ForeignKey"`
Name string `xml:"Name,attr"`
Local string `xml:"Local,attr"`
Foreign string `xml:"Foreign,attr"`
ForeignTable string `xml:"ForeignTable,attr"`
OnDelete *string `xml:"OnDelete,attr,omitempty"`
OnUpdate *string `xml:"OnUpdate,attr,omitempty"`
}
XMLForeignKey represents a foreign key constraint.
type XMLIndex ¶
type XMLIndex struct {
XMLName xml.Name `xml:"Index"`
Name string `xml:"Name,attr"`
Unique bool `xml:"Unique,attr,omitempty"`
Columns []XMLIndexColumn `xml:"Column"`
}
XMLIndex represents a table index in XML format.
type XMLIndexColumn ¶
XMLIndexColumn represents an index column.