Documentation
¶
Index ¶
- Constants
- Variables
- func InitializeModels(db *Database, metainfo []ModelMeta) error
- func NewGuid() string
- func SqlIdent(s string) bool
- type BaseModel
- func (m *BaseModel) Columns() []string
- func (m *BaseModel) DataDecode([]Data) error
- func (m *BaseModel) DataEncode([]Data) error
- func (m *BaseModel) InitialData(dbs *Session, tablename string) error
- func (m *BaseModel) IsAutoGuid() bool
- func (m *BaseModel) Limit() int
- func (m *BaseModel) Orders() []string
- func (m *BaseModel) PostSchema(dbs *Session, meta *ModelMeta) error
- func (m *BaseModel) PreSchema(dbs *Session, meta *ModelMeta) error
- func (m *BaseModel) TableName() string
- type ColumnMeta
- 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) DeleteGuid(guid string) error
- func (q *Query) FilterBy(column string, value any) *Query
- func (q *Query) Filters(expr string, args ...any) *Query
- func (q *Query) First() (Data, error)
- func (q *Query) GetGuid(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(orders ...string) *Query
- func (q *Query) Session() *Session
- func (q *Query) TableName(name string) *Query
- func (q *Query) Update(data Data) (int, error)
- func (q *Query) UpdateGuid(guid string, data Data) error
- type Session
- func (s *Session) Begin() error
- func (s *Session) Cancel()
- func (s *Session) Commit() error
- func (s *Session) Database() *Database
- func (s *Session) Exec(stmt string, params ...any) (int, error)
- func (s *Session) Fetch(stmt string, params ...any) ([]Data, error)
- func (s *Session) Ping() bool
- func (s *Session) Query(model Model) *Query
- func (s *Session) RollBack() error
- type SqlGenerator
- type StdSqlGenerator
- func (*StdSqlGenerator) Count(attrs *StmtAttrs) (string, []any)
- func (*StdSqlGenerator) Delete(attrs *StmtAttrs) (string, []any)
- func (*StdSqlGenerator) FormatStmt(stmt string) string
- func (*StdSqlGenerator) Insert(attrs *StmtAttrs, data Data) (string, []any)
- func (*StdSqlGenerator) Schema(tablename string, meta *TableMeta) []string
- func (*StdSqlGenerator) Select(attrs *StmtAttrs) (string, []any)
- func (*StdSqlGenerator) Update(attrs *StmtAttrs, data Data) (string, []any)
- type StmtAttrs
- type TableMeta
Constants ¶
const SQL_PLACEHOLDER = "?"
SQL Statment placeholder for variables.
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) // 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 ¶
InitializeModels creates and alter the database models schema, then adds the models intial 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 // 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) DataDecode ¶
DataDecode applies decoding on data after reading from database.
func (*BaseModel) DataEncode ¶
DataEncode applies encoding to data before writing to database.
func (*BaseModel) InitialData ¶
InitialData creates the initial data in table.
func (*BaseModel) IsAutoGuid ¶
IsAutoGuid returns true if the AutoGuid operations are enabled.
func (*BaseModel) PostSchema ¶
PostSchema is called after creating the table schema in database.
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 ¶
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 ¶
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)
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 Query ¶
type Query struct {
// contains filtered or unexported fields
}
Query represents the query object.
func (*Query) Delete ¶
Deletes data entries matching defined filters and returns the number of affected entries.
func (*Query) DeleteGuid ¶
DeleteGuid deletes only one element by guid.
func (*Query) GetGuid ¶
GetGuid is a short form to fetch only one element by guid. there must be a guid primary column in model.
func (*Query) Insert ¶
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) One ¶
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 ¶
OrderBy adds ordering expresion to the statment. orders has the format: "column ASC|DESC"
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 (*Session) Exec ¶
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 ¶
Fetch runs a query that returns rows. it takes the statment to run and the args are for any placeholder parameters in the query.
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
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: