sqldb

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2025 License: BSD-3-Clause Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const SQL_PLACEHOLDER = "?"

SQL Statment placeholder for variables.

Variables

View Source
var (
	// ErrError indicates the parent error.
	ErrError = errors.New("")

	// ErrDBHandler indicates an invalid or not defined database handler.
	ErrDBHandler = fmt.Errorf("%winvalid database handler", ErrError)
	// ErrDBEngine indicates an invalid or not defined database engine.
	ErrDBEngine = fmt.Errorf("%winvalid database engine", ErrError)
	// ErrDBSession indicates an invalid or not defined database session.
	ErrDBSession = fmt.Errorf("%winvalid database session", ErrError)

	// ErrDBConfig indicates an invalid or not defined database config.
	ErrDBConfig = fmt.Errorf("%winvalid database config", ErrError)
	// ErrDBPath indicates an invalid or not defined database path.
	ErrDBPath = fmt.Errorf("%winvalid database path", ErrDBConfig)
	// ErrDBName indicates an invalid or not defined database name.
	ErrDBName = fmt.Errorf("%winvalid database name", ErrDBConfig)
	// ErrDBAddr indicates an invalid or not defined database address.
	ErrDBAddr = fmt.Errorf("%winvalid database address", ErrDBConfig)

	// ErrOpen indicates the connection to database failed.
	ErrOpen = fmt.Errorf("%wconnection failed", ErrError)
	// ErrClosed indicates that the database connection is closed.
	ErrClosed = fmt.Errorf("%wconnection closed", ErrError)
	// ErrBreak indicates an operation interruption.
	ErrBreak = fmt.Errorf("%woperation break", ErrError)
	// ErrTimeout indicates that the database operation timed out.
	ErrTimeout = fmt.Errorf("%woperation timeout", ErrError)
	// ErrOperation indicates a database operation error.
	ErrOperation = fmt.Errorf("%woperation error", ErrError)
)

Functions

func InitializeModels

func InitializeModels(db *Database, metainfo []ModelMeta) error

InitializeModels creates and alter the database models schema, then adds the models intial data.

func NewGuid

func NewGuid() string

NewGuid generates a new string guid in hex format.

func SqlIdent

func SqlIdent(s string) bool

SqlIdent checks for a valid SQL identifier string.

Types

type BaseModel

type BaseModel struct {
	// DefaultTable defines the default tablename to use in statments.
	DefaultTable string
	// DefaultColumns defines the default set of column to use in statments.
	// leave empty to use all columns.
	DefaultColumns []string
	// DefaultOrders defines the default orders to use in statments.
	// columns in this list should be present in DefaultColumns.
	DefaultOrders []string
	// DefaultLimit defines the default limit to use in statments.
	DefaultLimit int
	// AutoGuid enables the auto guid operations: which are to create new guid
	// for inserts and prevent guid column change in updates.
	AutoGuid bool
}

BaseModel defines a base model structure.

func (*BaseModel) Columns

func (m *BaseModel) Columns() []string

Columns returns the table columns names to use in statments.

func (*BaseModel) DataDecode

func (m *BaseModel) DataDecode([]Data) error

DataDecode applies decoding on data after reading from database.

func (*BaseModel) DataEncode

func (m *BaseModel) DataEncode([]Data) error

DataEncode applies encoding to data before writing to database.

func (*BaseModel) InitialData

func (m *BaseModel) InitialData(dbs *Session, tablename string) error

InitialData creates the initial data in table.

func (*BaseModel) IsAutoGuid

func (m *BaseModel) IsAutoGuid() bool

IsAutoGuid returns true if the AutoGuid operations are enabled.

func (*BaseModel) Limit

func (m *BaseModel) Limit() int

Limit returns the number of rows to fetch in statments.

func (*BaseModel) Orders

func (m *BaseModel) Orders() []string

Orders returns the table order-by columns to use in statments.

func (*BaseModel) PostSchema

func (m *BaseModel) PostSchema(dbs *Session, meta *ModelMeta) error

PostSchema is called after creating the table schema in database.

func (*BaseModel) PreSchema

func (m *BaseModel) PreSchema(dbs *Session, meta *ModelMeta) error

PreSchema is called before creating the table schema in database.

func (*BaseModel) TableName

func (m *BaseModel) TableName() string

TableName returns the table name to use in statments.

type ColumnMeta

type ColumnMeta struct {
	// the column name, should be unique per table.
	Name string
	// the column data type as defined in SQL syntax.
	// ex. "VARCHAR(128) NOT NULL", "BOOLEAN NOT NULL DEFAULT false"
	Type string
	// set column primary key constraint.
	Primary bool
	// set column unique value constraint.
	Unique bool
	// set to create column index.
	Index bool
}

ColumnMeta represents column definition.

References:

type ConstraintMeta

type ConstraintMeta struct {
	// the constraint name, should be unique per table.
	Name string
	// the constraint definition as defined in SQL syntax.
	// ex. "PRIMARY KEY (col1,col2)"
	//     "FOREIGN KEY (col1) REFERENCES table1 (col2) ON UPDATE CASCADE"
	//     "UNIQUE (col1,col2)"
	//     "CHECK (col1 IN (0,1,2))"
	//     "CHECK (col1>=10 AND col2="val")"
	Definition string
}

ConstraintMeta represents constraint definitions.

References:

type Data

type Data = map[string]any

Data represents the table data. where each row is represented into a map for columns as keys and data as values.

type Database

type Database struct {
	// Log is the logger instance for database logging.
	Log *logging.Logger

	// OperationTimeout defines the timeout in seconds for database operation.
	// use 0 or negative value to disable operation timeout. (default 3.0 sec)
	OperationTimeout float64
	// RetryInterval defines the interval in seconds between operation retries.
	// trials are done untill operation is done or timeout is reached.
	// retry interval value must be > 0. (default 0.1 sec)
	RetryInterval float64
	// contains filtered or unexported fields
}

Database represents the database object.

func NewDatabase

func NewDatabase(log *logging.Logger, engine Engine, opts dictx.Dict) *Database

NewDatabase creates a new database handler.

The parsed options are:

  • operation_timeout: (float64) the timeout in seconds for database operation. use 0 or negative value to disable operation timeout. (default 3.0 sec)
  • retry_interval: (float64) the interval in seconds between operation retries. trials are done untill operation is done or timeout is reached. retry interval value must be > 0. (default 0.1 sec)

func (*Database) Backend

func (db *Database) Backend() string

Backend returns the database backend type.

func (*Database) Ping

func (db *Database) Ping() bool

Ping checks if database connection is active.

func (*Database) Query

func (db *Database) Query(model Model) *Query

Query returns a new query handler.

func (*Database) Session

func (db *Database) Session() *Session

Session returns a new session handler.

func (*Database) Shutdown

func (db *Database) Shutdown()

Shutdown closes all the database sessions.

type Engine

type Engine interface {
	// Backend returns the engine backend type.
	Backend() string

	// SqlDB create or return existing backend driver handler.
	SqlDB() (*sql.DB, error)
	// Release frees the backend driver resources between sessions.
	Release(*sql.DB) error
	// Close shutsdown the backend driver handler and free resources.
	Close(*sql.DB) error

	// CanRetryErr checks weather an operation error type can be retried.
	CanRetryErr(err error) bool

	// SqlGenerator returns the engine SQL statment generator.
	SqlGenerator() SqlGenerator
}

Engine defines the database engine interface.

type Model

type Model interface {
	// TableMeta returns the model table metainfo.
	TableMeta() *TableMeta

	// TableName returns the table name to use in statments.
	TableName() string
	// Columns returns the table columns to use in statments.
	Columns() []string
	// Orders returns the table order-by columns to use in statments.
	Orders() []string
	// Limit returns the number of rows to fetch in statments.
	Limit() int
	// IsAutoGuid returns true if the AutoGuid operations are enabled.
	IsAutoGuid() bool
	// DataEncode applies encoding to data before writing to database.
	DataEncode([]Data) error
	// DataDecode applies decoding on data after reading from database.
	DataDecode([]Data) error

	// PreSchema is called before creating the table schema in database.
	PreSchema(dbs *Session, meta *ModelMeta) error
	// PostSchema is called after creating the table schema in database.
	PostSchema(dbs *Session, meta *ModelMeta) error

	// InitialData creates the initial data in table.
	InitialData(dbs *Session, tablename string) error
}

Model defines the model interface.

type ModelMeta

type ModelMeta struct {
	Table string
	Model Model
}

ModelMeta represents link between tablename and table metainfo.

type Query

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

Query represents the query object.

func NewQuery

func NewQuery(dbs *Session, model Model) *Query

NewQuery creates a new query object

func (*Query) All

func (q *Query) All() ([]Data, error)

All returns all data entries matching defined filters.

func (*Query) Columns

func (q *Query) Columns(columns ...string) *Query

Columns sets the columns in statment.

func (*Query) Count

func (q *Query) Count() (int, error)

Counts the number of table entries matching defined filters.

func (*Query) Delete

func (q *Query) Delete() (int, error)

Deletes data entries matching defined filters and returns the number of affected entries.

func (*Query) DeleteGuid

func (q *Query) DeleteGuid(guid string) error

DeleteGuid deletes only one element by guid.

func (*Query) FilterBy

func (q *Query) FilterBy(column string, value any) *Query

FilterBy adds AND related filter to the statment.

func (*Query) Filters

func (q *Query) Filters(expr string, args ...any) *Query

Filters sets filtering expresion to the statment with args.

func (*Query) First

func (q *Query) First() (Data, error)

First returns the first data entry matching defined filters.

func (*Query) GetGuid

func (q *Query) GetGuid(guid string) (Data, error)

GetGuid is a short form to fetch only one element by guid. there must be a guid primary column in model.

func (*Query) GroupBy

func (q *Query) GroupBy(columns ...string) *Query

GroupBy adds grouping expresion to the statment.

func (*Query) Having

func (q *Query) Having(expr string, args ...any) *Query

Having adds having expr in the statment.

func (*Query) Insert

func (q *Query) Insert(data Data) (string, error)

Inserts new data entry and returns the guid for new entry. If Model AutoGuid is enabled, a new guid value is generated when the insert data have empty or no guid value.

func (*Query) Limit

func (q *Query) Limit(limit int) *Query

Limit adds limit in the statment.

func (*Query) Offset

func (q *Query) Offset(offset int) *Query

Offset add offset in the statment.

func (*Query) One

func (q *Query) One() (Data, error)

One returns and check that only one data entry matches the defined filters. there must be only one element matched or none, else an error is returned.

func (*Query) OrderBy

func (q *Query) OrderBy(orders ...string) *Query

OrderBy adds ordering expresion to the statment. orders has the format: "column ASC|DESC"

func (*Query) Session

func (q *Query) Session() *Session

Session returns the associated session handler

func (*Query) TableName

func (q *Query) TableName(name string) *Query

TableName sets the table name in statment.

func (*Query) Update

func (q *Query) Update(data Data) (int, error)

Updates data entries matching defined filters and returns the number of affected entries.

func (*Query) UpdateGuid

func (q *Query) UpdateGuid(guid string, data Data) error

UpdateGuid updates only one element by guid.

type Session

type Session struct {

	// OperationTimeout sets the timeout in seconds for operations.
	// use 0 or negative value to disable operation timeout. (default 5.0 sec)
	OperationTimeout float64
	// RetryInterval sets the interval in seconds between operation retries.
	// trials are done untill operation is done or timeout is reached.
	// retry interval value must be > 0. (default 0.1 sec)
	RetryInterval float64
	// contains filtered or unexported fields
}

Session represents a standard database Session.

func NewSession

func NewSession(db *Database) *Session

NewSession creates new database session.

func (*Session) Begin

func (s *Session) Begin() error

Begin starts a new transactional scope.

func (*Session) Cancel

func (s *Session) Cancel()

Cancel breaks all active session operation.

func (*Session) Commit

func (s *Session) Commit() error

Commit runs a commit action in transactional scope.

func (*Session) Database

func (s *Session) Database() *Database

Database returns the associated database handler

func (*Session) Exec

func (s *Session) Exec(stmt string, params ...any) (int, error)

Exec runs a query without returning any rows. it takes the statment to run and the args are for any placeholder parameters in the query.

func (*Session) Fetch

func (s *Session) Fetch(stmt string, params ...any) ([]Data, error)

Fetch runs a query that returns rows. it takes the statment to run and the args are for any placeholder parameters in the query.

func (*Session) Ping

func (s *Session) Ping() bool

Ping checks if the backend connection is active.

func (*Session) Query

func (s *Session) Query(model Model) *Query

Query returns a database query handler.

func (*Session) RollBack

func (s *Session) RollBack() error

RollBack runs a rollback action in transactional scope.

type SqlGenerator

type SqlGenerator interface {
	// FormatStmt prepares the statment placeholders format
	FormatStmt(stmt string) string

	// Select generates a SELECT statment
	Select(attrs *StmtAttrs) (string, []any)
	// Count generates a SELECT count(*) statment
	Count(attrs *StmtAttrs) (string, []any)
	// Insert generates an INSERT statment
	Insert(attrs *StmtAttrs, data Data) (string, []any)
	// Update generates an UPDATE statment
	Update(attrs *StmtAttrs, data Data) (string, []any)
	// Delete generates a DELETE statment
	Delete(attrs *StmtAttrs) (string, []any)

	// Schema generates table schema statments from metainfo
	Schema(tablename string, meta *TableMeta) []string
}

SqlGenerator interface defines SQL statments generator.

type StdSqlGenerator

type StdSqlGenerator struct{}

StdSqlGenerator represents a standard SQL statment generator.

func (*StdSqlGenerator) Count

func (*StdSqlGenerator) Count(attrs *StmtAttrs) (string, []any)

Count generates a SELECT count(*) statment

func (*StdSqlGenerator) Delete

func (*StdSqlGenerator) Delete(attrs *StmtAttrs) (string, []any)

Delete generates a DELETE statment

func (*StdSqlGenerator) FormatStmt

func (*StdSqlGenerator) FormatStmt(stmt string) string

FormatStmt prepares the statment placeholders format

func (*StdSqlGenerator) Insert

func (*StdSqlGenerator) Insert(attrs *StmtAttrs, data Data) (string, []any)

Insert generates an INSERT statment

func (*StdSqlGenerator) Schema

func (*StdSqlGenerator) Schema(tablename string, meta *TableMeta) []string

Schema generates table schema from table metainfo

func (*StdSqlGenerator) Select

func (*StdSqlGenerator) Select(attrs *StmtAttrs) (string, []any)

Select generates a SELECT statment from attrs.

func (*StdSqlGenerator) Update

func (*StdSqlGenerator) Update(attrs *StmtAttrs, data Data) (string, []any)

Update generates an UPDATE statment

type StmtAttrs

type StmtAttrs struct {
	Tablename   string
	Columns     []string
	Filters     string
	FiltersArgs []any
	Groupby     []string
	Orderby     []string
	Having      string
	HavingArgs  []any
	Offset      int
	Limit       int
}

StmtAttrs represents the SQL statment attributes.

type TableMeta

type TableMeta struct {
	// Table Columns meta
	Columns []ColumnMeta
	// Table Constraints as defined in SQL syntax. constraints are appended to
	// table after auto generated columns constraints.
	Constraints []ConstraintMeta
	// AutoGuid sets weather to enable AutoGuid operations, which is to
	// create a first primary guid column for table.
	// guid column is created with schema "guid VARCHAR(32) NOT NULL"
	AutoGuid bool
	// Extra options for backends.
	Args dictx.Dict
}

TableMeta represents table definition, columns and constraints.

References:

Jump to

Keyboard shortcuts

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