Documentation
¶
Overview ¶
Package database provides database connection and adapter management.
Index ¶
- func BuildInsertQuery(table string, columns []string, returning bool) string
- func BuildUpdateQuery(table string, setColumns []string, whereClause string) string
- func CloseTestDB()
- func CollectInt64s(rows *sql.Rows) ([]int64, error)
- func CollectInts(rows *sql.Rows) ([]int, error)
- 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 ConvertReturning(query string) (string, bool)
- func GetAbstractDB() (*sql.DB, error)
- func GetDB() (*sql.DB, error)
- func GetDBDriver() string
- func GetMigrationVersion(db *sql.DB) (uint, bool, error)
- func InitDB() error
- func InitTestDB() error
- func InitializeDefault() error
- func IsConnectionError(err error) bool
- func IsMySQL() bool
- func IsPostgreSQL() bool
- func IsTestDBOverride() bool
- func MustCloseRows(rows *sql.Rows, errPtr *error)
- func QualifiedTicketTypeColumn(alias string) string
- func QuoteIdentifier(name string) string
- func RegisterDriver(name string, factory func() DatabaseDriver)
- func RegisterDumpDriver(name string, factory func() DumpDriver)
- func ResetAdapterForTest()
- func ResetDB()
- func RowsErr(rows *sql.Rows, existingErr error) error
- func RunMigrations(db *sql.DB) (int, error)
- func ScanRows(rows *sql.Rows, scanFn ScanFunc) error
- func SetAdapter(adapter DBAdapter)
- func SetDB(db *sql.DB)
- func TicketTypeColumn() string
- type ColumnDef
- type ColumnDefinition
- type ColumnInfo
- type ConstraintDefinition
- type DBAdapter
- type DatabaseConfig
- type DatabaseDriver
- type DatabaseFactory
- type DatabaseFeatures
- type DatabaseType
- type DriverRegistry
- type DumpDriver
- type IDatabase
- type IDatabaseFactory
- type ITransaction
- type IndexDefinition
- type Manager
- 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 OracleDatabase
- func (o *OracleDatabase) Begin(ctx context.Context) (ITransaction, error)
- func (o *OracleDatabase) BeginTx(ctx context.Context, opts *sql.TxOptions) (ITransaction, error)
- func (o *OracleDatabase) BuildInsert(tableName string, data map[string]interface{}) (string, []interface{})
- func (o *OracleDatabase) BuildSelect(tableName string, columns []string, where string, orderBy string, limit int) string
- func (o *OracleDatabase) BuildUpdate(tableName string, data map[string]interface{}, where string, ...) (string, []interface{})
- func (o *OracleDatabase) Close() error
- func (o *OracleDatabase) Connect() error
- func (o *OracleDatabase) CreateIndex(ctx context.Context, tableName, indexName string, columns []string, ...) error
- func (o *OracleDatabase) CreateTable(ctx context.Context, definition *TableDefinition) error
- func (o *OracleDatabase) DropIndex(ctx context.Context, tableName, indexName string) error
- func (o *OracleDatabase) DropTable(ctx context.Context, tableName string) error
- func (o *OracleDatabase) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func (o *OracleDatabase) GetConcatFunction(fields []string) string
- func (o *OracleDatabase) GetConfig() DatabaseConfig
- func (o *OracleDatabase) GetDateFunction() string
- func (o *OracleDatabase) GetLimitClause(limit, offset int) string
- func (o *OracleDatabase) GetTableColumns(ctx context.Context, tableName string) ([]ColumnInfo, error)
- func (o *OracleDatabase) GetType() DatabaseType
- func (o *OracleDatabase) IsHealthy() bool
- func (o *OracleDatabase) Ping() error
- func (o *OracleDatabase) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func (o *OracleDatabase) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
- func (o *OracleDatabase) Quote(identifier string) string
- func (o *OracleDatabase) QuoteValue(value interface{}) string
- func (o *OracleDatabase) Stats() sql.DBStats
- func (o *OracleDatabase) SupportsReturning() bool
- func (o *OracleDatabase) TableExists(ctx context.Context, tableName string) (bool, error)
- type OracleTransaction
- func (t *OracleTransaction) Commit() error
- func (t *OracleTransaction) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func (t *OracleTransaction) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func (t *OracleTransaction) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
- func (t *OracleTransaction) 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 Query
- type QueryBuilder
- func (qb *QueryBuilder) DB() *sqlx.DB
- func (qb *QueryBuilder) Exec(query string, args ...interface{}) (sql.Result, error)
- func (qb *QueryBuilder) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func (qb *QueryBuilder) Get(dest interface{}, query string, args ...interface{}) error
- func (qb *QueryBuilder) GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
- func (qb *QueryBuilder) In(query string, args ...interface{}) (string, []interface{}, error)
- func (qb *QueryBuilder) Named(query string, arg interface{}) (string, []interface{}, error)
- func (qb *QueryBuilder) NamedExec(query string, arg interface{}) (sql.Result, error)
- func (qb *QueryBuilder) NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error)
- func (qb *QueryBuilder) NewSelect(columns ...string) *SelectBuilder
- func (qb *QueryBuilder) Query(query string, args ...interface{}) (*sql.Rows, error)
- func (qb *QueryBuilder) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func (qb *QueryBuilder) QueryRow(query string, args ...interface{}) *sql.Row
- func (qb *QueryBuilder) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
- func (qb *QueryBuilder) Rebind(query string) string
- func (qb *QueryBuilder) Select(dest interface{}, query string, args ...interface{}) error
- func (qb *QueryBuilder) SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
- type SQLServerDatabase
- func (s *SQLServerDatabase) Begin(ctx context.Context) (ITransaction, error)
- func (s *SQLServerDatabase) BeginTx(ctx context.Context, opts *sql.TxOptions) (ITransaction, error)
- func (s *SQLServerDatabase) BuildInsert(tableName string, data map[string]interface{}) (string, []interface{})
- func (s *SQLServerDatabase) BuildSelect(tableName string, columns []string, where string, orderBy string, limit int) string
- func (s *SQLServerDatabase) BuildUpdate(tableName string, data map[string]interface{}, where string, ...) (string, []interface{})
- func (s *SQLServerDatabase) Close() error
- func (s *SQLServerDatabase) Connect() error
- func (s *SQLServerDatabase) CreateIndex(ctx context.Context, tableName, indexName string, columns []string, ...) error
- func (s *SQLServerDatabase) CreateTable(ctx context.Context, definition *TableDefinition) error
- func (s *SQLServerDatabase) DropIndex(ctx context.Context, tableName, indexName string) error
- func (s *SQLServerDatabase) DropTable(ctx context.Context, tableName string) error
- func (s *SQLServerDatabase) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func (s *SQLServerDatabase) GetConcatFunction(fields []string) string
- func (s *SQLServerDatabase) GetConfig() DatabaseConfig
- func (s *SQLServerDatabase) GetDateFunction() string
- func (s *SQLServerDatabase) GetLimitClause(limit, offset int) string
- func (s *SQLServerDatabase) GetTableColumns(ctx context.Context, tableName string) ([]ColumnInfo, error)
- func (s *SQLServerDatabase) GetType() DatabaseType
- func (s *SQLServerDatabase) IsHealthy() bool
- func (s *SQLServerDatabase) Ping() error
- func (s *SQLServerDatabase) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func (s *SQLServerDatabase) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
- func (s *SQLServerDatabase) Quote(identifier string) string
- func (s *SQLServerDatabase) QuoteValue(value interface{}) string
- func (s *SQLServerDatabase) Stats() sql.DBStats
- func (s *SQLServerDatabase) SupportsReturning() bool
- func (s *SQLServerDatabase) TableExists(ctx context.Context, tableName string) (bool, error)
- type SQLServerTransaction
- func (t *SQLServerTransaction) Commit() error
- func (t *SQLServerTransaction) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func (t *SQLServerTransaction) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func (t *SQLServerTransaction) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
- func (t *SQLServerTransaction) Rollback() error
- type ScanFunc
- type SchemaConverter
- type SelectBuilder
- func (sb *SelectBuilder) From(table string) *SelectBuilder
- func (sb *SelectBuilder) Get(dest interface{}) error
- func (sb *SelectBuilder) GetContext(ctx context.Context, dest interface{}) error
- func (sb *SelectBuilder) GroupBy(columns ...string) *SelectBuilder
- func (sb *SelectBuilder) Having(condition string, args ...interface{}) *SelectBuilder
- func (sb *SelectBuilder) Join(join 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) Select(dest interface{}) error
- func (sb *SelectBuilder) SelectContext(ctx context.Context, dest interface{}) error
- func (sb *SelectBuilder) ToSQL() (string, []interface{}, error)
- func (sb *SelectBuilder) Where(condition string, args ...interface{}) *SelectBuilder
- func (sb *SelectBuilder) WhereIn(column string, values interface{}) *SelectBuilder
- type TableDefinition
- type TableSchema
- type Transaction
- type XMLColumn
- type XMLForeignKey
- type XMLIndex
- type XMLIndexColumn
- type XMLSchema
- type XMLTable
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BuildInsertQuery ¶
BuildInsertQuery builds an INSERT query compatible with the current database. Returns a query with ? placeholders - caller must use ConvertPlaceholders() before executing.
func BuildUpdateQuery ¶
BuildUpdateQuery builds an UPDATE query compatible with the current database. Returns a query with ? placeholders - caller must use ConvertPlaceholders() before executing. The whereClause should also use ? placeholders.
func CloseTestDB ¶
func CloseTestDB()
CloseTestDB is a no-op to avoid interfering with the global service-managed database connection. Left for API compatibility.
func CollectInt64s ¶
CollectInt64s scans rows containing a single int64 column.
func CollectInts ¶
CollectInts scans rows containing a single int column. This is a common pattern for queries like "SELECT id FROM table".
func CollectRows ¶
CollectRows is a generic helper that collects rows into a slice. The scanFn should scan a single row and return the value. This is a convenience wrapper around ScanRows for the common case.
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 ConvertReturning ¶
MySQL: Use LastInsertId() after insert.
func GetAbstractDB ¶
GetAbstractDB returns the global database instance (for backward compatibility).
func GetDB ¶
GetDB returns the database connection singleton from the service registry. Service registry is the single source of truth for database connections.
func GetMigrationVersion ¶
GetMigrationVersion returns the current migration version (public API).
func InitDB ¶
func InitDB() error
InitDB is kept for backward-compatibility with older tests; delegates to InitTestDB.
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 InitializeDefault ¶
func InitializeDefault() error
InitializeDefault initializes the database with default configuration from environment.
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 IsTestDBOverride ¶
func IsTestDBOverride() bool
IsTestDBOverride reports whether a test database has been explicitly injected via SetDB.
func MustCloseRows ¶
MustCloseRows closes rows and wraps any error with context. Use as: defer database.MustCloseRows(rows, &err) This ensures rows.Close() errors are captured even if the function already has an error.
func QualifiedTicketTypeColumn ¶
QualifiedTicketTypeColumn returns the column name prefixed with the provided alias.
func QuoteIdentifier ¶
QuoteIdentifier quotes table/column names based on database.
func RegisterDriver ¶
func RegisterDriver(name string, factory func() DatabaseDriver)
RegisterDriver registers a database driver.
func RegisterDumpDriver ¶
func RegisterDumpDriver(name string, factory func() DumpDriver)
RegisterDumpDriver registers a dump file driver.
func ResetAdapterForTest ¶
func ResetAdapterForTest()
ResetAdapterForTest clears the cached adapter so tests can rebuild state.
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 RowsErr ¶
RowsErr checks rows.Err() and returns it if non-nil, otherwise returns existingErr. This is useful for the common pattern of checking rows.Err() at the end of iteration. Deprecated: Use ScanRows or CollectRows instead which handle this automatically.
func RunMigrations ¶
RunMigrations runs database migrations using the migrate CLI tool. Returns the number of migrations applied and any error encountered.
func ScanRows ¶
ScanRows iterates over sql.Rows, calling scanFn for each row, and properly checks rows.Err() after iteration completes. This is the correct pattern for database row iteration that prevents silent iteration errors.
Usage:
var results []MyType
err := database.ScanRows(rows, func(rows *sql.Rows) error {
var item MyType
if err := rows.Scan(&item.Field1, &item.Field2); err != nil {
return err
}
results = append(results, item)
return nil
})
func SetAdapter ¶
func SetAdapter(adapter DBAdapter)
SetAdapter overrides the global adapter, primarily for tests.
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 ColumnDef ¶
type ColumnDef struct {
Type string `yaml:"type"` // varchar(200), int, serial, etc.
Required bool `yaml:"required"` // NOT NULL
Unique bool `yaml:"unique"`
Default interface{} `yaml:"default"`
Index bool `yaml:"index"`
}
ColumnDef represents a column definition.
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.
func LoadConfigFromEnv ¶
func LoadConfigFromEnv() DatabaseConfig
LoadConfigFromEnv loads database configuration from environment variables.
type DatabaseDriver ¶
type DatabaseDriver interface {
// Connection management
Connect(ctx context.Context, dsn string) error
Close() error
Ping(ctx context.Context) error
// Schema operations
CreateTable(schema TableSchema) (Query, error)
DropTable(tableName string) (Query, error)
TableExists(tableName string) (bool, error)
// CRUD operations
Insert(table string, data map[string]interface{}) (Query, error)
Update(table string, data map[string]interface{}, where string, whereArgs ...interface{}) (Query, error)
Delete(table string, where string, whereArgs ...interface{}) (Query, error)
Select(table string, columns []string, where string, whereArgs ...interface{}) (Query, error)
// Type mapping
MapType(schemaType string) string // e.g., "serial" -> "AUTO_INCREMENT" or "SERIAL"
// Feature detection
SupportsReturning() bool
SupportsLastInsertId() bool
SupportsArrays() bool
// Transaction support
BeginTx(ctx context.Context) (Transaction, error)
// Raw execution (for complex queries)
Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
}
DatabaseDriver interface for database abstraction.
func GetDriver ¶
func GetDriver(name string) (DatabaseDriver, error)
GetDriver returns a database driver by name.
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 list of supported database types.
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 DriverRegistry ¶
type DriverRegistry struct {
// contains filtered or unexported fields
}
DriverRegistry for managing available drivers.
type DumpDriver ¶
type DumpDriver interface {
// Parse and iterate through a dump file
Open(filename string) error
Close() error
// Read next statement from dump
NextStatement() (string, error)
// Get table schemas from dump
GetSchemas() ([]TableSchema, error)
// Stream data for a specific table
StreamTable(tableName string, callback func(row map[string]interface{}) error) error
// Write operations (for export)
WriteSchema(schema TableSchema) error
WriteData(table string, rows []map[string]interface{}) error
}
DumpDriver interface for SQL dump file handling.
func GetDumpDriver ¶
func GetDumpDriver(name string) (DumpDriver, error)
GetDumpDriver returns a dump driver by name.
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).
func GetDatabase ¶
func GetDatabase() IDatabase
GetDatabase returns the database abstraction instance.
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 Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager provides a singleton database instance using the abstraction layer.
func (*Manager) Initialize ¶
func (m *Manager) Initialize(config DatabaseConfig) error
Initialize sets up the database connection with the given configuration.
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 OracleDatabase ¶
type OracleDatabase struct {
// contains filtered or unexported fields
}
OracleDatabase implements IDatabase for Oracle.
func NewOracleDatabase ¶
func NewOracleDatabase(config DatabaseConfig) *OracleDatabase
NewOracleDatabase creates a new Oracle database instance.
func (*OracleDatabase) Begin ¶
func (o *OracleDatabase) Begin(ctx context.Context) (ITransaction, error)
Begin starts a transaction.
func (*OracleDatabase) BeginTx ¶
func (o *OracleDatabase) BeginTx(ctx context.Context, opts *sql.TxOptions) (ITransaction, error)
BeginTx starts a transaction with options.
func (*OracleDatabase) BuildInsert ¶
func (o *OracleDatabase) BuildInsert(tableName string, data map[string]interface{}) (string, []interface{})
BuildInsert builds an INSERT statement (stub implementation).
func (*OracleDatabase) BuildSelect ¶
func (o *OracleDatabase) BuildSelect(tableName string, columns []string, where string, orderBy string, limit int) string
BuildSelect builds a SELECT statement.
func (*OracleDatabase) BuildUpdate ¶
func (o *OracleDatabase) BuildUpdate(tableName string, data map[string]interface{}, where string, whereArgs []interface{}) (string, []interface{})
BuildUpdate builds an UPDATE statement (stub implementation).
func (*OracleDatabase) Close ¶
func (o *OracleDatabase) Close() error
Close closes the database connection.
func (*OracleDatabase) Connect ¶
func (o *OracleDatabase) Connect() error
Connect establishes connection to Oracle database (stub implementation).
func (*OracleDatabase) CreateIndex ¶
func (o *OracleDatabase) CreateIndex(ctx context.Context, tableName, indexName string, columns []string, unique bool) error
CreateIndex creates an index (stub implementation).
func (*OracleDatabase) CreateTable ¶
func (o *OracleDatabase) CreateTable(ctx context.Context, definition *TableDefinition) error
CreateTable creates a table from definition (stub implementation).
func (*OracleDatabase) DropIndex ¶
func (o *OracleDatabase) DropIndex(ctx context.Context, tableName, indexName string) error
DropIndex drops an index.
func (*OracleDatabase) DropTable ¶
func (o *OracleDatabase) DropTable(ctx context.Context, tableName string) error
DropTable drops a table.
func (*OracleDatabase) Exec ¶
func (o *OracleDatabase) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
Exec executes a query and returns the result.
func (*OracleDatabase) GetConcatFunction ¶
func (o *OracleDatabase) GetConcatFunction(fields []string) string
GetConcatFunction returns concatenation function.
func (*OracleDatabase) GetConfig ¶
func (o *OracleDatabase) GetConfig() DatabaseConfig
GetConfig returns the database configuration.
func (*OracleDatabase) GetDateFunction ¶
func (o *OracleDatabase) GetDateFunction() string
GetDateFunction returns current date function.
func (*OracleDatabase) GetLimitClause ¶
func (o *OracleDatabase) GetLimitClause(limit, offset int) string
GetLimitClause returns Oracle-specific LIMIT clause (using ROWNUM).
func (*OracleDatabase) GetTableColumns ¶
func (o *OracleDatabase) GetTableColumns(ctx context.Context, tableName string) ([]ColumnInfo, error)
GetTableColumns returns column information for a table (stub implementation).
func (*OracleDatabase) GetType ¶
func (o *OracleDatabase) GetType() DatabaseType
GetType returns the database type.
func (*OracleDatabase) IsHealthy ¶
func (o *OracleDatabase) IsHealthy() bool
IsHealthy checks if database is healthy.
func (*OracleDatabase) Ping ¶
func (o *OracleDatabase) Ping() error
Ping tests the database connection.
func (*OracleDatabase) Query ¶
func (o *OracleDatabase) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
Query executes a query and returns rows.
func (*OracleDatabase) Quote ¶
func (o *OracleDatabase) Quote(identifier string) string
Quote quotes an identifier (Oracle uses double quotes).
func (*OracleDatabase) QuoteValue ¶
func (o *OracleDatabase) QuoteValue(value interface{}) string
QuoteValue quotes a value.
func (*OracleDatabase) Stats ¶
func (o *OracleDatabase) Stats() sql.DBStats
Stats returns database connection statistics.
func (*OracleDatabase) SupportsReturning ¶
func (o *OracleDatabase) SupportsReturning() bool
SupportsReturning returns true for Oracle (RETURNING INTO).
func (*OracleDatabase) TableExists ¶
TableExists checks if a table exists (stub implementation).
type OracleTransaction ¶
type OracleTransaction struct {
// contains filtered or unexported fields
}
OracleTransaction implements ITransaction for Oracle.
func (*OracleTransaction) Commit ¶
func (t *OracleTransaction) Commit() error
func (*OracleTransaction) Rollback ¶
func (t *OracleTransaction) 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 Query ¶
type Query struct {
SQL string
Args []interface{}
}
Query represents a SQL query with arguments.
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) ExecContext ¶
func (qb *QueryBuilder) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
ExecContext executes a query with context without returning rows.
func (*QueryBuilder) Get ¶
func (qb *QueryBuilder) Get(dest interface{}, query string, args ...interface{}) error
Get executes a query expecting a single row and scans into dest (struct).
func (*QueryBuilder) GetContext ¶
func (qb *QueryBuilder) GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
GetContext executes a query with context expecting a single row.
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) Named ¶
func (qb *QueryBuilder) Named(query string, arg interface{}) (string, []interface{}, error)
Named returns a query with named parameter support. Example: Named("SELECT * FROM users WHERE name = :name", map[string]interface{}{"name": "john"}).
func (*QueryBuilder) NamedExec ¶
func (qb *QueryBuilder) NamedExec(query string, arg interface{}) (sql.Result, error)
NamedExec executes a named query.
func (*QueryBuilder) NamedExecContext ¶
func (qb *QueryBuilder) NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error)
NamedExecContext executes a named query with context.
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) QueryContext ¶
func (qb *QueryBuilder) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
QueryContext executes a query with context 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) QueryRowContext ¶
func (qb *QueryBuilder) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
QueryRowContext executes a query with context expecting a single row.
func (*QueryBuilder) Rebind ¶
func (qb *QueryBuilder) Rebind(query string) string
Rebind converts a query with ? placeholders to the appropriate format for the database. This allows writing queries in MySQL format and auto-converting for PostgreSQL.
func (*QueryBuilder) Select ¶
func (qb *QueryBuilder) Select(dest interface{}, query string, args ...interface{}) error
Select executes a query and scans results into dest (slice of structs).
func (*QueryBuilder) SelectContext ¶
func (qb *QueryBuilder) SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
SelectContext executes a query with context and scans results into dest.
type SQLServerDatabase ¶
type SQLServerDatabase struct {
// contains filtered or unexported fields
}
SQLServerDatabase implements IDatabase for Microsoft SQL Server.
func NewSQLServerDatabase ¶
func NewSQLServerDatabase(config DatabaseConfig) *SQLServerDatabase
NewSQLServerDatabase creates a new SQL Server database instance.
func (*SQLServerDatabase) Begin ¶
func (s *SQLServerDatabase) Begin(ctx context.Context) (ITransaction, error)
Begin starts a transaction.
func (*SQLServerDatabase) BeginTx ¶
func (s *SQLServerDatabase) BeginTx(ctx context.Context, opts *sql.TxOptions) (ITransaction, error)
BeginTx starts a transaction with options.
func (*SQLServerDatabase) BuildInsert ¶
func (s *SQLServerDatabase) BuildInsert(tableName string, data map[string]interface{}) (string, []interface{})
BuildInsert builds an INSERT statement (stub implementation).
func (*SQLServerDatabase) BuildSelect ¶
func (s *SQLServerDatabase) BuildSelect(tableName string, columns []string, where string, orderBy string, limit int) string
BuildSelect builds a SELECT statement.
func (*SQLServerDatabase) BuildUpdate ¶
func (s *SQLServerDatabase) BuildUpdate(tableName string, data map[string]interface{}, where string, whereArgs []interface{}) (string, []interface{})
BuildUpdate builds an UPDATE statement (stub implementation).
func (*SQLServerDatabase) Close ¶
func (s *SQLServerDatabase) Close() error
Close closes the database connection.
func (*SQLServerDatabase) Connect ¶
func (s *SQLServerDatabase) Connect() error
Connect establishes connection to SQL Server database (stub implementation).
func (*SQLServerDatabase) CreateIndex ¶
func (s *SQLServerDatabase) CreateIndex(ctx context.Context, tableName, indexName string, columns []string, unique bool) error
CreateIndex creates an index (stub implementation).
func (*SQLServerDatabase) CreateTable ¶
func (s *SQLServerDatabase) CreateTable(ctx context.Context, definition *TableDefinition) error
CreateTable creates a table from definition (stub implementation).
func (*SQLServerDatabase) DropIndex ¶
func (s *SQLServerDatabase) DropIndex(ctx context.Context, tableName, indexName string) error
DropIndex drops an index.
func (*SQLServerDatabase) DropTable ¶
func (s *SQLServerDatabase) DropTable(ctx context.Context, tableName string) error
DropTable drops a table.
func (*SQLServerDatabase) Exec ¶
func (s *SQLServerDatabase) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
Exec executes a query and returns the result.
func (*SQLServerDatabase) GetConcatFunction ¶
func (s *SQLServerDatabase) GetConcatFunction(fields []string) string
GetConcatFunction returns concatenation function.
func (*SQLServerDatabase) GetConfig ¶
func (s *SQLServerDatabase) GetConfig() DatabaseConfig
GetConfig returns the database configuration.
func (*SQLServerDatabase) GetDateFunction ¶
func (s *SQLServerDatabase) GetDateFunction() string
GetDateFunction returns current date function.
func (*SQLServerDatabase) GetLimitClause ¶
func (s *SQLServerDatabase) GetLimitClause(limit, offset int) string
GetLimitClause returns SQL Server-specific LIMIT clause (using OFFSET/FETCH).
func (*SQLServerDatabase) GetTableColumns ¶
func (s *SQLServerDatabase) GetTableColumns(ctx context.Context, tableName string) ([]ColumnInfo, error)
GetTableColumns returns column information for a table (stub implementation).
func (*SQLServerDatabase) GetType ¶
func (s *SQLServerDatabase) GetType() DatabaseType
GetType returns the database type.
func (*SQLServerDatabase) IsHealthy ¶
func (s *SQLServerDatabase) IsHealthy() bool
IsHealthy checks if database is healthy.
func (*SQLServerDatabase) Ping ¶
func (s *SQLServerDatabase) Ping() error
Ping tests the database connection.
func (*SQLServerDatabase) Query ¶
func (s *SQLServerDatabase) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
Query executes a query and returns rows.
func (*SQLServerDatabase) QueryRow ¶
func (s *SQLServerDatabase) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
QueryRow executes a query and returns a single row.
func (*SQLServerDatabase) Quote ¶
func (s *SQLServerDatabase) Quote(identifier string) string
Quote quotes an identifier (SQL Server uses square brackets).
func (*SQLServerDatabase) QuoteValue ¶
func (s *SQLServerDatabase) QuoteValue(value interface{}) string
QuoteValue quotes a value.
func (*SQLServerDatabase) Stats ¶
func (s *SQLServerDatabase) Stats() sql.DBStats
Stats returns database connection statistics.
func (*SQLServerDatabase) SupportsReturning ¶
func (s *SQLServerDatabase) SupportsReturning() bool
SupportsReturning returns true for SQL Server (OUTPUT clause).
func (*SQLServerDatabase) TableExists ¶
TableExists checks if a table exists (stub implementation).
type SQLServerTransaction ¶
type SQLServerTransaction struct {
// contains filtered or unexported fields
}
SQLServerTransaction implements ITransaction for SQL Server.
func (*SQLServerTransaction) Commit ¶
func (t *SQLServerTransaction) Commit() error
func (*SQLServerTransaction) Rollback ¶
func (t *SQLServerTransaction) Rollback() error
type ScanFunc ¶
ScanFunc is a function that scans a single row. It receives the rows object and should call rows.Scan() to extract values. Return an error to abort iteration, or nil to continue.
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) Get ¶
func (sb *SelectBuilder) Get(dest interface{}) error
Get executes the query expecting a single row.
func (*SelectBuilder) GetContext ¶
func (sb *SelectBuilder) GetContext(ctx context.Context, dest interface{}) error
GetContext executes the query with context expecting a single row.
func (*SelectBuilder) GroupBy ¶
func (sb *SelectBuilder) GroupBy(columns ...string) *SelectBuilder
GroupBy adds GROUP BY columns.
func (*SelectBuilder) Having ¶
func (sb *SelectBuilder) Having(condition string, args ...interface{}) *SelectBuilder
Having adds a HAVING condition.
func (*SelectBuilder) Join ¶
func (sb *SelectBuilder) Join(join string) *SelectBuilder
Join adds a JOIN clause.
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) Select ¶
func (sb *SelectBuilder) Select(dest interface{}) error
Select executes the query and scans into dest.
func (*SelectBuilder) SelectContext ¶
func (sb *SelectBuilder) SelectContext(ctx context.Context, dest interface{}) error
SelectContext executes the query with context and scans into dest.
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.
func (*SelectBuilder) WhereIn ¶
func (sb *SelectBuilder) WhereIn(column string, values interface{}) *SelectBuilder
WhereIn adds a WHERE IN condition.
type TableDefinition ¶
type TableDefinition struct {
Name string
Columns []ColumnDefinition
Indexes []IndexDefinition
Constraints []ConstraintDefinition
}
TableDefinition represents a database table structure.
type TableSchema ¶
type TableSchema struct {
Name string `yaml:"name"`
PK string `yaml:"pk"` // Primary key field name (default: "id")
Columns map[string]ColumnDef `yaml:"columns"`
Indexes []string `yaml:"indexes"`
Unique []string `yaml:"unique"`
Timestamps bool `yaml:"timestamps"` // Add create_time, change_time automatically
Meta map[string]interface{} `yaml:"meta"` // Driver-specific metadata
}
TableSchema represents a table definition from YAML.
type Transaction ¶
type Transaction interface {
Commit() error
Rollback() error
Exec(query string, args ...interface{}) (sql.Result, error)
Query(query string, args ...interface{}) (*sql.Rows, error)
QueryRow(query string, args ...interface{}) *sql.Row
}
Transaction represents a database transaction.
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.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
drivers
|
|
|
mysql
Package mysql provides the MySQL database driver implementation.
|
Package mysql provides the MySQL database driver implementation. |
|
postgres
Package postgres provides the PostgreSQL database driver implementation.
|
Package postgres provides the PostgreSQL database driver implementation. |
|
sqlite
Package sqlite provides the SQLite database driver implementation.
|
Package sqlite provides the SQLite database driver implementation. |
|
Package schema provides database schema loading and management.
|
Package schema provides database schema loading and management. |