sqldb

package
v0.0.0-...-e80c572 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	// Defined backends.
	BACKEND_NONE   = Backend(0)
	BACKEND_SQLITE = Backend(1)
	BACKEND_MYSQL  = Backend(2)
	BACKEND_PGSQL  = Backend(3)
	BACKEND_MSSQL  = Backend(4)
)
View Source
const SQL_PLACEHOLDER = "?"

SQL statment variable placeholder

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)
	// ErrDBBackend indicates an invalid or not defined database backend.
	ErrDBBackend = fmt.Errorf("%winvalid database backend", 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)
	// ErrDBHost indicates an invalid or not defined database host.
	ErrDBHost = fmt.Errorf("%winvalid database host", ErrDBConfig)
	// ErrDBPort indicates an invalid or not defined database port number.
	ErrDBPort = fmt.Errorf("%winvalid database port", 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 InitializeDatabase

func InitializeDatabase(db *Database, metainfo []TableModelMeta) error

InitializeDatabase first creates and alter the models table schema, then add the intial tables 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 Backend

type Backend uint8

Backend represents the databases type.

func (Backend) String

func (b Backend) String() string

represent the Backend type string format

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
	// 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. does nothing by default.

func (*BaseModel) DataEncode

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

DataEncode applies encoding to data before writing to database. does nothing by default.

func (*BaseModel) IsAutoGuid

func (m *BaseModel) IsAutoGuid() bool

IsAutoGuid returns true if the AutoGuid operations are enabled.

func (*BaseModel) Orders

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

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

func (*BaseModel) TableName

func (m *BaseModel) TableName() string

TableName returns the table name to use in statments.

type BaseModelMeta

type BaseModelMeta TableMeta

BaseModelMeta defines a base model metainfo structure.

func (*BaseModelMeta) AlterSchema

func (m *BaseModelMeta) AlterSchema(s *Session, tablename string) error

AlterSchema modifies the table schema in database. default nothing.

func (*BaseModelMeta) CreateSchema

func (m *BaseModelMeta) CreateSchema(s *Session, tablename string) error

CreateSchema creates the table schema in database.

func (*BaseModelMeta) InitialData

func (m *BaseModelMeta) InitialData(s *Session, tablename string) error

InitialData creates the initial data in table. default none.

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 defines strcture holding column definitions and constraints.

References:

type Config

type Config struct {
	// database name or path
	Database string
	// database host for client/server type databases.
	Host string
	// database port number for client/server type databases.
	Port int
	// database access username
	Username string
	// database access password
	Password string
	// connection options for backends.
	ConnectArgs string
}

Config represents the database configuration params.

func NewConfig

func NewConfig(d dictx.Dict) *Config

NewConfig creates a new database Config object.

The parsed options are:

  • database: (string) the database name or path.
  • host: (string) host for client/server type databases.
  • port: (int) port number for client/server type databases.
  • username: (string) database access username.
  • password: (string) database access password.
  • connect_args: (string) connection options for backends.

func (*Config) String

func (cfg *Config) String() string

represent the Config in string format

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 defines strcture holding constraints definitions.

References:

type Data

type Data = map[string]any

Data type defines the table column data. where each column data is represented into a map for columns as keys and data as values.

type Database

type Database struct {

	// DBLog is the logger instance for database logging.
	DBLog *logging.Logger

	// OperationTimeout defines the timeout in seconds for database operation.
	// use 0 or negative value to disable operation timeout. (default 5.0 sec)
	OperationTimeout float64
	// RetryInterval defines the time 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(engine Engine, dblog *logging.Logger, opts dictx.Dict) (*Database, error)

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 5.0 sec)
  • retry_interval: (float64) the time 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() Backend

Backend returns the database backend type.

func (*Database) Close

func (db *Database) Close()

Closes all the database sessions and operations.

func (*Database) IsActive

func (db *Database) IsActive() bool

Checks if database connection is active.

func (*Database) NewSession

func (db *Database) NewSession() (*Session, error)

NewSession creates a new session object.

type Engine

type Engine interface {
	// Backend returns the engine backend type.
	Backend() Backend
	// Config returns the engine connection config.
	Config() *Config
	// SqlDB returns the driver database handler.
	SqlDB() *sql.DB
	// Open the engine backend connection.
	Open() error
	// Close the engine backend connection.
	Close()
	// Checks weather an operation error type can be retried.
	CanRetryErr(err error) bool
	// GenSchema generates table schema.
	GenSchema(tablename string, meta *TableMeta) string
}

type Model

type Model interface {
	// 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
	// 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
}

Model represents the model interface.

type ModelMeta

type ModelMeta interface {
	// CreateSchema creates the table schema in database.
	CreateSchema(s *Session, tablename string) error
	// AlterSchema modifies the table schema in database.
	AlterSchema(s *Session, tablename string) error
	// InitialData creates the initial data in table.
	InitialData(s *Session, tablename string) error
}

ModelMeta represents the model metainfo interface.

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 from table 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 from table matching defined filters and returns the number of affected entries.

func (*Query) Filter

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

Filter adds filter expresion to the statment with args. using this function overides any filters added using the Query.FilterBy function.

func (*Query) FilterBy

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

FilterBy adds multiple AND related filters to the statment. using this function overides any filters added using the Query.Filter function.

func (*Query) First

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

First returns the first data entry from table matching defined filters.

func (*Query) Get

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

Get is a short form to fetch only one element by column named guid.

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 statment

func (*Query) Insert

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

Inserts data into table 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 statment

func (*Query) Offset

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

Offset add offset in statment

func (*Query) One

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

One returns only one data entry from table matching defined filters. there must be none or only one element matched else an error is returned.

func (*Query) OrderBy

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

OrderBy adds ordering expresion to the statment. order_expr has the format: "column_name ASC|DESC"

func (*Query) TableName

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

TableName sets the runtime table name in statment.

func (*Query) Update

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

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

type Session

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

Session represents the database session object.

func (*Session) Begin

func (s *Session) Begin() error

Begin starts a new transactional scope.

func (*Session) Break

func (s *Session) Break()

Breaks active session operation.

func (*Session) Commit

func (s *Session) Commit() error

Commit runs a commit action in transactional scope.

func (*Session) Execute

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

Executes 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) FetchAll

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

FetchAll 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) Query

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

Query creates new query object on current session.

func (*Session) RollBack

func (s *Session) RollBack() error

RollBack runs a rollback action in transactional scope.

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 specific backends. each option is prefixed with the
	// backend name plus underscore. ex: "sqlite_<OPTION_NAME>"
	Args dictx.Dict
}

TableMeta defines strcture holding table definitions and constraints.

References:

type TableModelMeta

type TableModelMeta struct {
	TableName string
	ModelMeta ModelMeta
}

TableModelMeta represents link between table name and model metainfo.

Jump to

Keyboard shortcuts

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