Documentation
¶
Index ¶
- Constants
- Variables
- func InitializeDatabase(db *Database, metainfo []TableModelMeta) error
- func NewGuid() string
- func SqlIdent(s string) bool
- type Backend
- type BaseModel
- type BaseModelMeta
- type ColumnMeta
- type Config
- type ConstraintMeta
- type Data
- type Database
- type Engine
- type Model
- type ModelMeta
- type Query
- func (q *Query) All() ([]Data, error)
- func (q *Query) Columns(columns ...string) *Query
- func (q *Query) Count() (int, error)
- func (q *Query) Delete() (int, error)
- func (q *Query) Filter(expr string, args ...any) *Query
- func (q *Query) FilterBy(column string, value any) *Query
- func (q *Query) First() (Data, error)
- func (q *Query) Get(guid string) (Data, error)
- func (q *Query) GroupBy(columns ...string) *Query
- func (q *Query) Having(expr string, args ...any) *Query
- func (q *Query) Insert(data Data) (string, error)
- func (q *Query) Limit(limit int) *Query
- func (q *Query) Offset(offset int) *Query
- func (q *Query) One() (Data, error)
- func (q *Query) OrderBy(order_expr ...string) *Query
- func (q *Query) TableName(name string) *Query
- func (q *Query) Update(data Data) (int, error)
- type Session
- func (s *Session) Begin() error
- func (s *Session) Break()
- func (s *Session) Commit() error
- func (s *Session) Execute(stmt string, params ...any) (int, error)
- func (s *Session) FetchAll(stmt string, params ...any) ([]Data, error)
- func (s *Session) Query(model Model) *Query
- func (s *Session) RollBack() error
- type TableMeta
- type TableModelMeta
Constants ¶
const ( // Defined backends. BACKEND_NONE = Backend(0) BACKEND_SQLITE = Backend(1) BACKEND_MYSQL = Backend(2) BACKEND_PGSQL = Backend(3) BACKEND_MSSQL = Backend(4) )
const SQL_PLACEHOLDER = "?"
SQL statment variable placeholder
Variables ¶
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.
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 // 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) DataDecode ¶
DataDecode applies decoding on data after reading from database. does nothing by default.
func (*BaseModel) DataEncode ¶
DataEncode applies encoding to data before writing to database. does nothing by default.
func (*BaseModel) IsAutoGuid ¶
IsAutoGuid returns true if the AutoGuid operations are enabled.
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 ¶
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.
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 ¶
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 ¶
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) Close ¶
func (db *Database) Close()
Closes all the database sessions and operations.
func (*Database) NewSession ¶
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 (*Query) Delete ¶
Deletes data from table matching defined filters and returns the number of affected entries.
func (*Query) Filter ¶
Filter adds filter expresion to the statment with args. using this function overides any filters added using the Query.FilterBy function.
func (*Query) FilterBy ¶
FilterBy adds multiple AND related filters to the statment. using this function overides any filters added using the Query.Filter function.
func (*Query) Insert ¶
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) One ¶
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 ¶
OrderBy adds ordering expresion to the statment. order_expr has the format: "column_name ASC|DESC"
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session represents the database session object.
func (*Session) Execute ¶
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 ¶
FetchAll runs a query that returns rows. it takes the statment to run and the args are for any placeholder parameters in the query.
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 ¶
TableModelMeta represents link between table name and model metainfo.