engine

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package engine defines the database engine abstraction layer.

The engine package provides interfaces that encapsulate all database-specific behavior, enabling true multi-database support. Each database dialect (SQLite, PostgreSQL, MySQL) implements the Engine interface.

Usage:

engine, err := engine.New("postgresql")
if err != nil {
    return err
}

typeMapper := engine.TypeMapper()
typeInfo := typeMapper.SQLToGo("UUID", false)

parser := engine.SchemaParser()
catalog, diags, err := parser.Parse(ctx, path, content)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsDialectSupported

func IsDialectSupported(dialect string) bool

IsDialectSupported reports whether a dialect is supported.

func ListRegistered

func ListRegistered() []string

ListRegistered returns all registered dialect names.

func Register

func Register(dialect string, factory Factory)

Register allows external packages to register custom engines. This is useful for plugins or custom database support.

Types

type ConnectionPoolConfig

type ConnectionPoolConfig struct {
	// MaxOpenConns is the maximum number of open connections to the database.
	// A value of 0 means no limit.
	MaxOpenConns int

	// MaxIdleConns is the maximum number of connections in the idle connection pool.
	// A value of 0 means no idle connections are retained.
	MaxIdleConns int

	// ConnMaxLifetime is the maximum amount of time a connection may be reused.
	// Expired connections may be closed lazily before reuse.
	// A value of 0 means connections are not closed due to age.
	ConnMaxLifetime time.Duration

	// ConnMaxIdleTime is the maximum amount of time a connection may be idle
	// before being closed.
	// A value of 0 means connections are not closed due to inactivity.
	ConnMaxIdleTime time.Duration
}

ConnectionPoolConfig defines recommended connection pool settings for a database.

type Diagnostic

type Diagnostic struct {
	Path     string
	Line     int
	Column   int
	Message  string
	Severity Severity
}

Diagnostic represents an issue found during query analysis.

type Engine

type Engine interface {
	// Name returns the engine identifier (e.g., "sqlite", "postgresql", "mysql").
	Name() string

	// TypeMapper returns the type mapper for SQL-to-language conversions.
	TypeMapper() TypeMapper

	// SchemaParser returns the DDL parser for this database dialect.
	SchemaParser() schemaparser.SchemaParser

	// SQLGenerator returns the SQL DDL generator for this dialect.
	SQLGenerator() SQLGenerator

	// DefaultDriver returns the default Go driver import path for this database.
	DefaultDriver() string

	// SupportsFeature reports whether this engine supports a specific feature.
	SupportsFeature(feature Feature) bool

	// ConnectionPool returns recommended connection pool settings.
	ConnectionPool() ConnectionPoolConfig

	// IsolationLevels returns supported isolation levels and default.
	IsolationLevels() (supported []IsolationLevel, defaultLevel IsolationLevel)

	// QueryHints returns available query hints for this database.
	QueryHints() []QueryHint
}

Engine encapsulates all database-specific behavior. Each database dialect implements this interface to provide its unique characteristics for schema parsing, type mapping, and code generation.

func FromConfig

func FromConfig(cfg config.Database, opts Options) (Engine, error)

FromConfig creates an Engine from a configuration.

func MustNew

func MustNew(dialect string, opts Options) Engine

MustNew creates a new Engine or panics if the dialect is not supported. Useful for tests and initialization code.

func New

func New(dialect string, opts Options) (Engine, error)

New creates a new Engine for the specified database dialect. Returns an error if the dialect is not supported.

type Factory

type Factory func(opts Options) (Engine, error)

Factory is a function that creates an Engine instance.

type Feature

type Feature int

Feature represents a database capability that may vary between engines.

const (
	// FeatureTransactions indicates support for ACID transactions.
	FeatureTransactions Feature = iota

	// FeatureForeignKeys indicates support for foreign key constraints.
	FeatureForeignKeys

	// FeatureWindowFunctions indicates support for window functions (ROW_NUMBER, etc).
	FeatureWindowFunctions

	// FeatureCTEs indicates support for Common Table Expressions (WITH clauses).
	FeatureCTEs

	// FeatureUpsert indicates support for upsert operations (INSERT ON CONFLICT/ON DUPLICATE KEY).
	FeatureUpsert

	// FeatureReturning indicates support for RETURNING clause.
	FeatureReturning

	// FeatureJSON indicates support for JSON/JSONB data types and operations.
	FeatureJSON

	// FeatureArrays indicates support for array data types.
	FeatureArrays

	// FeatureFullTextSearch indicates support for full-text search.
	FeatureFullTextSearch

	// FeaturePreparedStatements indicates support for prepared statements.
	FeaturePreparedStatements

	// FeatureAutoIncrement indicates support for auto-increment/serial columns.
	FeatureAutoIncrement

	// FeatureViews indicates support for CREATE VIEW statements.
	FeatureViews

	// FeatureIndexes indicates support for CREATE INDEX statements.
	FeatureIndexes
)

func (Feature) String

func (f Feature) String() string

String returns the human-readable name of a feature.

type IndexSuggestion

type IndexSuggestion struct {
	Table   string
	Columns []string
	Reason  string
}

IndexSuggestion represents a recommended index for query optimization.

type IsolationLevel

type IsolationLevel int

IsolationLevel represents a transaction isolation level.

const (
	// IsolationLevelDefault uses the database's default isolation level.
	IsolationLevelDefault IsolationLevel = iota

	// IsolationLevelReadUncommitted allows reading uncommitted changes.
	IsolationLevelReadUncommitted

	// IsolationLevelReadCommitted prevents reading uncommitted changes.
	IsolationLevelReadCommitted

	// IsolationLevelWriteCommitted is a PostgreSQL-specific level.
	IsolationLevelWriteCommitted

	// IsolationLevelRepeatableRead ensures consistent reads within a transaction.
	IsolationLevelRepeatableRead

	// IsolationLevelSnapshot provides snapshot isolation (SQL Server style).
	IsolationLevelSnapshot

	// IsolationLevelSerializable provides the strictest isolation.
	IsolationLevelSerializable

	// IsolationLevelLinearizable provides linearizable consistency.
	IsolationLevelLinearizable
)

func (IsolationLevel) String

func (i IsolationLevel) String() string

String returns the human-readable name of an isolation level.

type Options

type Options struct {
	// EmitPointersForNull enables pointer types for nullable values.
	EmitPointersForNull bool

	// CustomTypes provides custom type mappings.
	CustomTypes []config.CustomTypeMapping
}

Options configures an engine instance.

type QueryAnalyzer

type QueryAnalyzer interface {
	// ValidateQuery checks if a query is valid for this dialect.
	// Returns a list of diagnostics for any issues found.
	ValidateQuery(query string) []Diagnostic

	// SuggestIndexes recommends indexes that could improve query performance.
	SuggestIndexes(query string, catalog *model.Catalog) []IndexSuggestion
}

QueryAnalyzer provides dialect-specific query validation and optimization.

type QueryHint

type QueryHint struct {
	// Name is the identifier for this hint (e.g., "INDEX", "USE_INDEX").
	Name string

	// Description explains what this hint does and when to use it.
	Description string

	// Syntax shows the SQL syntax for this hint.
	// Example: "/*+ INDEX(table_name index_name) */" for Oracle-style hints.
	Syntax string
}

QueryHint represents a database-specific query optimization hint.

type Registry

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

Registry manages engine factories for different database dialects.

func (*Registry) IsRegistered

func (r *Registry) IsRegistered(dialect string) bool

IsRegistered reports whether a dialect is registered.

func (*Registry) List

func (r *Registry) List() []string

List returns all registered dialect names.

func (*Registry) New

func (r *Registry) New(dialect string, opts Options) (Engine, error)

New creates an Engine for the specified dialect. Returns an error if the dialect is not registered.

func (*Registry) Register

func (r *Registry) Register(dialect string, factory Factory)

Register adds an engine factory to the registry. Panics if the dialect is already registered.

type SQLGenerator

type SQLGenerator interface {
	// GenerateTable creates a CREATE TABLE statement for the given table.
	GenerateTable(table *model.Table) string

	// GenerateIndex creates a CREATE INDEX statement.
	GenerateIndex(index *model.Index, tableName string) string

	// GenerateColumnDef creates a column definition clause.
	GenerateColumnDef(column *model.Column) string

	// Dialect returns the target SQL dialect identifier.
	Dialect() string
}

SQLGenerator generates SQL DDL statements in a specific dialect.

type Severity

type Severity int

Severity indicates the seriousness of a diagnostic.

const (
	// SeverityWarning indicates a potential issue that doesn't prevent code generation.
	SeverityWarning Severity = iota
	// SeverityError indicates a fatal issue that prevents code generation.
	SeverityError
)

type TypeInfo

type TypeInfo struct {
	// GoType is the Go type name (e.g., "string", "int64", "uuid.UUID").
	GoType string

	// UsesSQLNull indicates if this type uses database/sql null types
	// (e.g., sql.NullString, sql.NullInt64).
	UsesSQLNull bool

	// Import is the import path if an external package is needed.
	// Empty for standard library types.
	Import string

	// Package is the package name for the import (e.g., "uuid", "sql").
	// Empty for standard library types.
	Package string

	// IsPointer indicates if this type is naturally a pointer.
	IsPointer bool
}

TypeInfo describes a resolved programming language type.

type TypeMapper

type TypeMapper interface {
	// SQLToGo converts a SQL type to Go type information.
	// The nullable parameter indicates if the column allows NULL values.
	SQLToGo(sqlType string, nullable bool) TypeInfo

	// SQLToSemantic converts a SQL type to a semantic type category.
	// This is used for cross-language type mapping.
	SQLToSemantic(sqlType string, nullable bool) types.SemanticType

	// GetRequiredImports returns the imports needed for generated code.
	// The returned map is from import path to package alias.
	GetRequiredImports() map[string]string

	// SupportsPointersForNull reports whether this engine supports using
	// pointers for nullable types instead of sql.Null* types.
	SupportsPointersForNull() bool
}

TypeMapper handles SQL type to programming language type conversions.

Directories

Path Synopsis
Package builtin registers all built-in database engines.
Package builtin registers all built-in database engines.
Package mysql provides the MySQL database engine implementation.
Package mysql provides the MySQL database engine implementation.
Package postgres provides the PostgreSQL database engine implementation.
Package postgres provides the PostgreSQL database engine implementation.
Package sqlite provides the SQLite database engine implementation.
Package sqlite provides the SQLite database engine implementation.

Jump to

Keyboard shortcuts

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