model

package
v0.8.7 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNoRows      = sql.ErrNoRows
	ErrUniqueValue = errors.New("goent: unique constraint violation")
	ErrForeignKey  = errors.New("goent: foreign key constraint violation")
	ErrBadRequest  = errors.New("goent: bad request")

	ErrInvalidDatabase    = errors.New("goent: invalid database, the target needs to be a struct")
	ErrInvalidDBField     = errors.New("goent: invalid database, last struct field needs to be goent.DB")
	ErrDBNotFound         = errors.New("goent: db not found")
	ErrFieldNotFound      = errors.New("goent: field or table not found")
	ErrColumnNotFound     = errors.New("goent: column not found")
	ErrNoPrimaryKey       = errors.New("goent: struct does not have a primary key set")
	ErrSliceTypeMigration = errors.New("goent: cannot migrate slice type")
	ErrDuplicateIndex     = errors.New("goent: struct has two or more indexes with same name but different uniqueness/function")
	ErrForeignKeyNotFound = errors.New("goent: foreign key not found")
	ErrMiddleTableNotSet  = errors.New("goent: middle table not configured for M2M relation")
)

Functions

func NewColumnNotFoundError added in v0.8.4

func NewColumnNotFoundError(column string) error

NewColumnNotFoundError creates an error indicating that the specified column was not found.

func NewDuplicateIndexError added in v0.8.4

func NewDuplicateIndexError(tableName, indexName string) error

NewDuplicateIndexError creates an error indicating duplicate index definitions with conflicting settings.

func NewFieldNotFoundError added in v0.8.4

func NewFieldNotFoundError(field string) error

NewFieldNotFoundError creates an error indicating that the specified field or table was not found.

func NewForeignKeyNotFoundError added in v0.8.4

func NewForeignKeyNotFoundError(fk string) error

NewForeignKeyNotFoundError creates an error indicating that the specified foreign key was not found.

func NewNoPrimaryKeyError added in v0.8.4

func NewNoPrimaryKeyError(typeName string) error

NewNoPrimaryKeyError creates an error indicating that the struct does not have a primary key set.

Types

type Attribute

type Attribute struct {
	Table string // Table name
	Name  string // Column name
}

Attribute represents a column in a table It contains the table name and column name

type AttributeMigrate

type AttributeMigrate struct {
	Nullable     bool   // Whether the column allows null values
	FieldName    string // Go struct field name
	Name         string // Column name
	EscapingName string // Escaped column name
	DataType     string // Data type
	Default      string // Default value
	FieldPos     int    // Field position in struct (for ordering)
}

type ColumnNotFoundError added in v0.8.4

type ColumnNotFoundError struct {
	Column string
}

ColumnNotFoundError is returned when a column cannot be found in a table.

func (*ColumnNotFoundError) Error added in v0.8.4

func (e *ColumnNotFoundError) Error() string

type Config

type Config interface {
	// Name returns the name of the database
	Name() string
	// GetDatabaseConfig returns the database configuration
	GetDatabaseConfig() *DatabaseConfig
}

type Connection

type Connection interface {
	// ExecContext executes a SQL statement without returning rows
	ExecContext(ctx context.Context, query *Query) error
	// QueryRowContext executes a SQL query and returns a single row
	QueryRowContext(ctx context.Context, query *Query) Row
	// QueryContext executes a SQL query and returns multiple rows
	QueryContext(ctx context.Context, query *Query) (Rows, error)
}

type DatabaseConfig

type DatabaseConfig struct {
	Logger           Logger        // Logger interface for logging
	IncludeArguments bool          // Whether to include arguments in logs
	QueryThreshold   time.Duration // Threshold for slow query warnings
	// contains filtered or unexported fields
}

func (*DatabaseConfig) AddSchema

func (c *DatabaseConfig) AddSchema(s string)

AddSchema adds a schema to the list of schemas for the database It appends the provided schema to the current list

func (*DatabaseConfig) ErrorHandler

func (c *DatabaseConfig) ErrorHandler(ctx context.Context, err error) error

ErrorHandler logs the database error using the configured logger It logs the error and returns it

func (*DatabaseConfig) ErrorQueryHandler

func (c *DatabaseConfig) ErrorQueryHandler(ctx context.Context, query Query) error

ErrorQueryHandler logs the query error using the configured logger It translates the error and logs it with query details

func (*DatabaseConfig) InfoHandler

func (c *DatabaseConfig) InfoHandler(ctx context.Context, query Query)

InfoHandler logs the query information using the configured logger It logs query details including duration and SQL

func (*DatabaseConfig) Init

func (c *DatabaseConfig) Init(driverName string, errorTranslator func(err error) error)

Init initializes the database configuration with the given driver name and error translator It resets and initializes the configuration with the provided values

func (*DatabaseConfig) InitCallback

func (c *DatabaseConfig) InitCallback() func() error

InitCallback returns the initialization callback function for the database It returns the currently set initialization callback

func (*DatabaseConfig) Schemas

func (c *DatabaseConfig) Schemas() []string

Schemas returns the list of schemas configured for the database It returns the currently configured schemas

func (*DatabaseConfig) SetInitCallback

func (c *DatabaseConfig) SetInitCallback(f func() error)

SetInitCallback sets the initialization callback function for the database It sets the function to be called during initialization

func (*DatabaseConfig) SetSchemas

func (c *DatabaseConfig) SetSchemas(s []string)

SetSchemas sets the list of schemas for the database It replaces the current schemas with the provided list

type Driver

type Driver interface {
	// MigrateContext migrates the database schema
	MigrateContext(context.Context, *Migrator) error

	// DropTable drops a table from the database schema
	DropTable(schema, table string) error
	// DropColumn drops a column from a table in the database schema
	DropColumn(schema, table, column string) error
	// RenameColumn renames a column in a table in the database schema
	RenameColumn(schema, table, oldColumn, newName string) error
	// RenameTable renames a table in the database schema
	RenameTable(schema, table, newName string) error

	// AddLogger adds a logger to the database driver
	AddLogger(Logger, error) error
	// ErrorTranslator translates database errors
	ErrorTranslator() func(err error) error
	// KeywordHandler handles SQL keywords in the database driver
	KeywordHandler(string) string
	// FormatTableName formats the table name in the database driver
	FormatTableName(schema, table string) string
	// SupportsReturning checks if the database driver supports RETURNING clause
	SupportsReturning() bool

	// NewConnection creates a new database connection
	NewConnection() Connection
	// NewTransaction creates a new database transaction
	NewTransaction(ctx context.Context, opts *sql.TxOptions) (Transaction, error)

	// Init initializes the database schema
	Init() error
	// Close closes the database driver
	Close() error
	// Stats returns the database statistics
	Stats() sql.DBStats
	// Config represents a database configuration
	Config
}

type DuplicateIndexError added in v0.8.4

type DuplicateIndexError struct {
	TableName string
	IndexName string
}

DuplicateIndexError is returned when two or more indexes have the same name but different settings.

func (*DuplicateIndexError) Error added in v0.8.4

func (e *DuplicateIndexError) Error() string

type FieldNotFoundError added in v0.8.4

type FieldNotFoundError struct {
	Field string
}

FieldNotFoundError is returned when a field or table cannot be found.

func (*FieldNotFoundError) Error added in v0.8.4

func (e *FieldNotFoundError) Error() string

type ForeignKeyNotFoundError added in v0.8.4

type ForeignKeyNotFoundError struct {
	ForeignKey string
}

ForeignKeyNotFoundError is returned when a foreign key column cannot be found.

func (*ForeignKeyNotFoundError) Error added in v0.8.4

func (e *ForeignKeyNotFoundError) Error() string

type IndexMigrate

type IndexMigrate struct {
	Name         string             // Index name
	EscapingName string             // Escaped index name
	Unique       bool               // Whether the index is unique
	Func         string             // Index function (e.g., "UPPER")
	Attributes   []AttributeMigrate // Attributes included in the index
}

type JoinType

type JoinType string
const (
	Join      JoinType = "JOIN"       // JOIN or OUTER JOIN clause
	LeftJoin  JoinType = "LEFT JOIN"  // LEFT JOIN clause
	RightJoin JoinType = "RIGHT JOIN" // RIGHT JOIN clause
	InnerJoin JoinType = "INNER JOIN" // INNER JOIN clause
)

type Logger

type Logger interface {
	// InfoContext logs information messages
	InfoContext(ctx context.Context, msg string, kv ...any)
	// WarnContext logs warning messages
	WarnContext(ctx context.Context, msg string, kv ...any)
	// ErrorContext logs error messages
	ErrorContext(ctx context.Context, msg string, kv ...any)
}

type ManyToSomeMigrate

type ManyToSomeMigrate struct {
	TargetTable          string  // Target table name
	TargetColumn         string  // Target column name
	EscapingTargetTable  string  // Escaped target table name
	EscapingTargetColumn string  // Escaped target column name
	TargetSchema         *string // Target schema name
	AttributeMigrate             // Embedded attribute information
}

func (ManyToSomeMigrate) EscapingTargetTableName

func (m ManyToSomeMigrate) EscapingTargetTableName() string

EscapingTargetTableName returns the escaped target table name with schema if available It formats the escaped target table name as schema.table if a schema is provided

type Migrator

type Migrator struct {
	Tables  map[string]*TableMigrate // Tables to migrate
	Schemas []string                 // Schemas to use
	Error   error                    // Migration error
}

type NoPrimaryKeyError added in v0.8.4

type NoPrimaryKeyError struct {
	TypeName string
}

NoPrimaryKeyError is returned when a struct does not have a primary key defined.

func (*NoPrimaryKeyError) Error added in v0.8.4

func (e *NoPrimaryKeyError) Error() string

type OneToSomeMigrate

type OneToSomeMigrate struct {
	IsOneToMany          bool    // Whether the relationship is one-to-many
	TargetTable          string  // Target table name
	TargetColumn         string  // Target column name
	EscapingTargetTable  string  // Escaped target table name
	EscapingTargetColumn string  // Escaped target column name
	TargetSchema         *string // Target schema name
	AttributeMigrate             // Embedded attribute information
}

func (OneToSomeMigrate) EscapingTargetTableName

func (o OneToSomeMigrate) EscapingTargetTableName() string

EscapingTargetTableName returns the escaped target table name with schema if available It formats the escaped target table name as schema.table if a schema is provided

type OrderedColumn added in v0.8.6

type OrderedColumn struct {
	Pos    int // Field position in struct
	IsPK   bool
	PK     *PrimaryKeyMigrate
	Attr   *AttributeMigrate
	OneTo  *OneToSomeMigrate
	ManyTo *ManyToSomeMigrate
}

OrderedColumn represents a column with its position for ordering

func (OrderedColumn) Name added in v0.8.6

func (c OrderedColumn) Name() string

Name returns the column name

type PrimaryKeyMigrate

type PrimaryKeyMigrate struct {
	AutoIncrement    bool // Whether the primary key is auto-incrementing
	AttributeMigrate      // Embedded attribute information
}

type Query

type Query struct {
	RawSql        string        // Raw SQL statement
	Arguments     []any         // Query arguments
	QueryDuration time.Duration // Execution duration
	Err           error         // Execution error
}

func CreateQuery

func CreateQuery(rawSql string, args []any) Query

CreateQuery creates a new Query with the given raw SQL and arguments It initializes a Query struct with the provided SQL and arguments

func (*Query) Finish added in v0.8.4

func (q *Query) Finish(ctx context.Context, dc *DatabaseConfig, start time.Time) error

func (*Query) WrapExec added in v0.8.4

func (q *Query) WrapExec(ctx context.Context, conn Connection, dc *DatabaseConfig) error

func (*Query) WrapQuery added in v0.8.4

func (q *Query) WrapQuery(ctx context.Context, conn Connection, dc *DatabaseConfig) (Rows, error)

func (*Query) WrapQueryRow added in v0.8.4

func (q *Query) WrapQueryRow(ctx context.Context, conn Connection, dc *DatabaseConfig) (Row, error)

type QueryType

type QueryType uint
const (
	SelectQuery     QueryType // SELECT query
	SelectJoinQuery           // SELECT query with JOIN clause
	InsertQuery               // INSERT query
	InsertAllQuery            // INSERT ALL query
	UpdateQuery               // UPDATE query
	UpdateJoinQuery           // UPDATE query with JOIN clause
	DeleteQuery               // DELETE query
	RawQuery                  // Raw SQL query
)

type Row

type Row interface {
	// Scan scans the row values into the provided destinations
	Scan(dest ...any) error
}

type Rows

type Rows interface {
	// Close closes the result set
	Close() error
	// Next advances to the next row
	Next() bool
	// Row represents a single row in the result set
	Row
}

type SavePoint

type SavePoint interface {
	// Commit commits the savepoint
	Commit() error
	// Rollback rolls back the savepoint
	Rollback() error
}

type Table

type Table struct {
	Schema *string // Schema name (optional)
	Name   string  // Table name
}

func (Table) String

func (t Table) String() string

String returns the table name with schema if available It formats the table name as schema.table if a schema is provided

type TableMigrate

type TableMigrate struct {
	Name         string              // Table name
	EscapingName string              // Escaped table name
	Schema       *string             // Schema name
	Migrated     bool                // Whether the table has been migrated
	PrimaryKeys  []PrimaryKeyMigrate // Primary key columns
	Indexes      []IndexMigrate      // Indexes
	Attributes   []AttributeMigrate  // Columns
	ManyToSomes  []ManyToSomeMigrate // Many-to-one/many-to-many relationships
	OneToSomes   []OneToSomeMigrate  // One-to-one/one-to-many relationships
}

func (TableMigrate) EscapingTableName

func (t TableMigrate) EscapingTableName() string

EscapingTableName returns the escaped table name with schema if available It formats the escaped table name as schema.table if a schema is provided

func (*TableMigrate) GetOrderedColumns added in v0.8.6

func (t *TableMigrate) GetOrderedColumns() []OrderedColumn

GetOrderedColumns returns all columns ordered by their field position

type Transaction

type Transaction interface {
	// Connection represents the underlying database connection
	Connection
	// Commit commits the transaction
	Commit() error
	// Rollback rolls back the transaction
	Rollback() error
	// SavePoint creates a savepoint in the transaction
	SavePoint() (SavePoint, error)
}

Jump to

Keyboard shortcuts

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