yaorm

package module
Version: v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2021 License: MIT Imports: 16 Imported by: 0

README

Yet Another ORM

Build Status Go Report Card Coverage Status

This is another ORM. Another one.

Concept

  • Declare a bit more of code to handle all your models the same way
  • Use filters to select data
  • With good coding practices, it becomes easy to use and easy to read

Must-do

  • Models should compose yaorm.DatabaseModel in order to correctly implement the yaorm.Model interface
  • Filters should compose yaorm.ModelFilter in order to correctly implement the yaorm.Filter interface

Models by examples

Declaration

package main

import (
    "time"

    "github.com/geoffreybauduin/yaorm"
)

func init() {
    yaorm.NewTable("test", "category", &Category{})
}

type Category struct {
    // Always compose this struct
    yaorm.DatabaseModel
    ID        int64     `db:"id"`
    Name      string    `db:"name"`
    CreatedAt time.Time `db:"created_at"`
    UpdatedAt time.Time `db:"updated_at"`
}

Loading a model

Using a generic function
package main

import (
    "time"

    "github.com/geoffreybauduin/yaorm"
    "github.com/geoffreybauduin/yaorm/yaormfilter"
)

func init() {
    yaorm.NewTable("test", "category", &Category{}).WithFilter(&CategoryFilter{})
}

type Category struct {
    // Always compose this struct
    yaorm.DatabaseModel
    ID        int64     `db:"id"`
    Name      string    `db:"name"`
    CreatedAt time.Time `db:"created_at"`
    UpdatedAt time.Time `db:"updated_at"`
}

type CategoryFilter struct {
    // Always compose this struct
    yaormfilter.ModelFilter
    FilterID   yaormfilter.ValueFilter `filter:"id"`
}

func GetCategory(dbp yaorm.DBProvider, id int64) (*Category, error) {
    category, err := yaorm.GenericSelectOne(dbp, &filter.CategoryFilter{FilterID: yaormfilter.Equals(id)})
    return category.(*Category), err
}

// GetCategoryLight only loads "id" and "name" columns (other fields
// won't be initialized in returned *Category).
func GetCategoryLight(dbp yaorm.DBProvider, id int64) (*Category, error) {
    f := filter.CategoryFilter{FilterID: yaormfilter.Equals(id)}
    f.LoadColumns("id", "name")
    category, err := yaorm.GenericSelectOne(dbp, &f)
    return category.(*Category), err
}

// GetCategoryNoDates does not load "created_at" and "updated_at"
// columns (these fields won't be initialized in returned *Category).
func GetCategoryNoDates(dbp yaorm.DBProvider, id int64) (*Category, error) {
    f := filter.CategoryFilter{FilterID: yaormfilter.Equals(id)}
    f.DontLoadColumns("created_at", "updated_at")
    category, err := yaorm.GenericSelectOne(dbp, &f)
    return category.(*Category), err
}

Using the model's load function
package main

import (
    "time"

    "github.com/geoffreybauduin/yaorm"
    "github.com/geoffreybauduin/yaorm/yaormfilter"
)

func init() {
    yaorm.NewTable("test", "category", &Category{}).WithFilter(&CategoryFilter{})
}

type Category struct {
    // Always compose this struct
    yaorm.DatabaseModel
    ID        int64     `db:"id"`
    Name      string    `db:"name"`
    CreatedAt time.Time `db:"created_at"`
    UpdatedAt time.Time `db:"updated_at"`
}

type CategoryFilter struct {
    // Always compose this struct
    yaormfilter.ModelFilter
    FilterID   yaormfilter.ValueFilter `filter:"id"`
}

// Load loads into the model filtering by the already defined values
// it is necessary to override this function if you want to be able to automatically Load models
func (c *Category) Load(dbp yaorm.DBProvider) error {
    return yaorm.GenericSelectOneFromModel(dbp, c)
}

func GetCategory(dbp yaorm.DBProvider, id int64) (*Category, error) {
    category := &Category{ID: id}
    return category, category.Load(dbp)
}

Saving a model

NB: saving includes both inserting and updating

Using a generic function
package main

import (
    "time"

    "github.com/geoffreybauduin/yaorm"
    "github.com/geoffreybauduin/yaorm/yaormfilter"
)

func init() {
    yaorm.NewTable("test", "category", &Category{}).WithFilter(&CategoryFilter{})
}

type Category struct {
    // Always compose this struct
    yaorm.DatabaseModel
    ID        int64     `db:"id"`
    Name      string    `db:"name"`
    CreatedAt time.Time `db:"created_at"`
    UpdatedAt time.Time `db:"updated_at"`
}

type CategoryFilter struct {
    // Always compose this struct
    yaormfilter.ModelFilter
    FilterID   yaormfilter.ValueFilter `filter:"id"`
}

func CreateCategory(dbp yaorm.DBProvider, name string) (*Category, error) {
    category := &testdata.Category{Name: name}
    return category, yaorm.GenericSave(category)
}

Using the model's save function
package main

import (
    "time"

    "github.com/geoffreybauduin/yaorm"
    "github.com/geoffreybauduin/yaorm/yaormfilter"
)

func init() {
    yaorm.NewTable("test", "category", &Category{}).WithFilter(&CategoryFilter{})
}

type Category struct {
    // Always compose this struct
    yaorm.DatabaseModel
    ID        int64     `db:"id"`
    Name      string    `db:"name"`
    CreatedAt time.Time `db:"created_at"`
    UpdatedAt time.Time `db:"updated_at"`
}

type CategoryFilter struct {
    // Always compose this struct
    yaormfilter.ModelFilter
    FilterID   yaormfilter.ValueFilter `filter:"id"`
}

// Save saves the current category inside the database
// it is necessary to declare this method if you want to really save the model
func (c *Category) Save() error {
    return yaorm.GenericSave(c)
}

func CreateCategory(dbp yaorm.DBProvider, name string) (*Category, error) {
    category := &testdata.Category{Name: name}
    category.Save(dbp)
    return category, category.Save()
}

Joining

package main

import (
    "time"

    "github.com/geoffreybauduin/yaorm"
    "github.com/geoffreybauduin/yaorm/yaormfilter"
)

func init() {
    yaorm.NewTable("test", "category", &Category{}).WithFilter(&CategoryFilter{})
    yaorm.NewTable("test", "post", &Post{}).WithFilter(&PostFilter{})
}

type Category struct {
    // Always compose this struct
    yaorm.DatabaseModel
    ID        int64     `db:"id"`
    Name      string    `db:"name"`
    CreatedAt time.Time `db:"created_at"`
    UpdatedAt time.Time `db:"updated_at"`
}

type CategoryFilter struct {
    // Always compose this struct
    yaormfilter.ModelFilter
    FilterID   yaormfilter.ValueFilter `filter:"id"`
}

type Post struct {
    yaorm.DatabaseModel
    ID         int64     `db:"id"`
    Subject    string    `db:"subject"`
    CategoryID int64     `db:"category_id"`
    Category   *Category `db:"-" filterload:"category,category_id"`
}

type PostFilter struct {
    yaormfilter.ModelFilter
    FilterCategory yaormfilter.Filter      `filter:"category,join,id,category_id" filterload:"category"`
}

func GetPostsFromCategory(dbp yaorm.DBProvider, category *Category) {
    posts, err := yaorm.GenericSelectAll(dbp, &PostFilter{FilterCategory: &CategoryFilter{ID: yaormfilter.Equals(category.ID)}})
}

And more...

In testdata folder

The theory

Here's a list of what you can do with this library

Filtering on any model

You can filter on any model you declare by also coding a Filter object

  • Define the tag filter on your filter struct, should be the same value than the db field you want to filter on
  • Declare your filter when you declare your sql table using the WithFilter helper.

No need to write SQL queries anymore.

package main

import (
    "time"

    "github.com/geoffreybauduin/yaorm"
    "github.com/geoffreybauduin/yaorm/yaormfilter"
)

func init() {
    yaorm.NewTable("test", "category", &Category{}).WithFilter(&CategoryFilter{})
}

type Category struct {
    // Always compose this struct
    yaorm.DatabaseModel
    ID        int64     `db:"id"`
    Name      string    `db:"name"`
    CreatedAt time.Time `db:"created_at"`
    UpdatedAt time.Time `db:"updated_at"`
}

type CategoryFilter struct {
    // Always compose this struct
    yaormfilter.ModelFilter
    FilterID   yaormfilter.ValueFilter `filter:"id"`
}

Automatic loading

You can automatically load your nested objects with a bit of code.

  • Define the tag filterload on your model inside the linked struct
  • Define the tag filterload on your filter inside the linked struct (should be the same tag value), and specify the corresponding key to match with (here it's Post.category_id)
  • Define the subquery loading function with WithSubqueryloading helper while you declare the sql table
package main

import (
    "time"

    "github.com/geoffreybauduin/yaorm"
    "github.com/geoffreybauduin/yaorm/yaormfilter"
)

func init() {
    yaorm.NewTable("test", "category", &Category{}).WithFilter(&CategoryFilter{}).WithSubqueryloading(
        func(dbp yaorm.DBProvider, ids []interface{}) (interface{}, error) {
            return yaorm.GenericSelectAll(dbp, NewCategoryFilter().ID(yaormfilter.In(ids...)))
        },
        "id",
    )
    yaorm.NewTable("test", "post", &Post{}).WithFilter(&PostFilter{})
}

type Category struct {
    // Always compose this struct
    yaorm.DatabaseModel
    ID        int64     `db:"id"`
    Name      string    `db:"name"`
    CreatedAt time.Time `db:"created_at"`
    UpdatedAt time.Time `db:"updated_at"`
}

type CategoryFilter struct {
    // Always compose this struct
    yaormfilter.ModelFilter
    FilterID     yaormfilter.ValueFilter `filter:"id"`
    FilterName   yaormfilter.ValueFilter `filter:"name"`
}

func NewCategoryFilter() *CategoryFilter {
    return &CategoryFilter{}
}

func (cf *CategoryFilter) ID (v yaormfilter.ValueFilter) *CategoryFilter {
    cf.FilterID = v
    return cf
}

func (cf *CategoryFilter) Name (v yaormfilter.ValueFilter) *CategoryFilter {
    cf.FilterName = v
    return cf
}


func (cf *CategoryFilter) Subqueryload() yaormfilter.Filter {
    cf.AllowSubqueryload()
    return cf
}

type Post struct {
    yaorm.DatabaseModel
    ID         int64     `db:"id"`
    Subject    string    `db:"subject"`
    CategoryID int64     `db:"category_id"`
    Category   *Category `db:"-" filterload:"category,category_id"`
}

type PostFilter struct {
    yaormfilter.ModelFilter
    FilterCategory yaormfilter.Filter      `filter:"category,join,id,category_id" filterload:"category"`
}

func NewPostFilter() *PostFilter {
    return &PostFilter{}
}

func (pf *PostFilter) Category (category yaormfilter.Filter) *PostFilter {
    pf.FilterCategory = category
    return pf
}


func GetPostsFromCategory(dbp yaorm.DBProvider, category *Category) {
    posts, err := yaorm.GenericSelectAll(dbp, NewPostFilter().Category(
        NewCategoryFilter().Name(category.Name).Subqueryload(),
    )
    // and then posts[0].Category won't be nil
}

Hooks

SQL Executor

It is possible to define custom hooks while executing SQL requests. Possible hooks are currently:

  • Before/After SelectOne
  • Before/After Select (multiple)

Your executor should implement yaorm.ExecutorHook interface, and can compose yaorm.DefaultExecutorHook to avoid any issues with updates (like a missing method to implement). The executor hook can be declared while registering the database

package main

import (
    "log"
    "github.com/geoffreybauduin/yaorm"
)

type LoggingExecutor struct {
    *yaorm.DefaultExecutorHook
}

func (h LoggingExecutor) AfterSelectOne(query string, args ...interface{})  {
    log.Printf("SQL Query: %s %+v\n", query, args)
}

func main() {
    defer func() {
        os.Remove("/tmp/test_test.sqlite")
        yaorm.UnregisterDB("test")
    }()
    yaorm.RegisterDB(&yaorm.DatabaseConfiguration{
        Name:             "test",
        DSN:              "/tmp/test_test.sqlite",
        System:           yaorm.DatabaseSqlite3,
        AutoCreateTables: true,
        ExecutorHook:     &LoggingExecutor{},
    })
    // now it will use the executor
}

Good practices

Filters

  • Define filters to be able to chain functions, it is a lot more readable !
type CategoryFilter struct {
    // Always compose this struct
    yaormfilter.ModelFilter
    FilterID     yaormfilter.ValueFilter `filter:"id"`
    FilterName   yaormfilter.ValueFilter `filter:"name"`
}

func NewCategoryFilter() *CategoryFilter {
    return &CategoryFilter{}
}

func (cf *CategoryFilter) ID (v yaormfilter.ValueFilter) *CategoryFilter {
    cf.FilterID = v
    return cf
}

func (cf *CategoryFilter) Name (v yaormfilter.ValueFilter) *CategoryFilter {
    cf.FilterName = v
    return cf
}

func main() {
    f := NewCategoryFilter().ID(yaormfilter.Equals(1))
}

Contributing

Contributions are welcomed. Don't hesitate to open a PR.

License

MIT License

Copyright (c) 2017 Geoffrey Bauduin

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Index

Constants

View Source
const (
	DatabaseCapacitySchema = iota ^ 42
	DatabaseCapacityUUID
)

Variables

View Source
var (
	// ErrTableEmpty is returned when a registered model has no exported fields
	ErrTableEmpty = errors.Errorf("Table is empty")
	// ErrTableNotFound is returned when a table cannot be found
	ErrTableNotFound = errors.NotFoundf("Table")
	// ErrDbNotFound is returned when a database cannot be found
	ErrDbNotFound = errors.NotFoundf("Database")
)
View Source
var (
	ErrDatabaseConflict = errors.Errorf("Database name conflicts with existing")
)

Functions

func GenericCount

func GenericCount(dbp DBProvider, filter yaormfilter.Filter) (uint64, error)

GenericCount selects counts the row in the database panics if filter or dbp is nil

func GenericDelete added in v1.1.0

func GenericDelete(m Model) (int64, error)

GenericDelete will delete the provided model from its database Returns the number of rows deleted

func GenericInsert

func GenericInsert(m Model) error

GenericInsert inserts the provided model in the database panics if model is nil or not linked to dbp

func GenericSave

func GenericSave(m Model) error

GenericSave updates or inserts the provided model in the database panics if model is nil or not linked to dbp

func GenericSelectOneFromModel

func GenericSelectOneFromModel(dbp DBProvider, m Model) error

GenericSelectOneFromModel selects one row in the database from a model value panics if filter or dbp is nil

func GenericSelectOneWithModel

func GenericSelectOneWithModel(dbp DBProvider, filter yaormfilter.Filter, m Model) error

GenericSelectOneWithModel selects one row in the database providing the destination model directly panics if filter or dbp is nil

func GenericUpdate

func GenericUpdate(m Model) error

GenericUpdate updates the provided model in the database panics if model is nil or not linked to dbp

func RegisterDB

func RegisterDB(config *DatabaseConfiguration) error

RegisterDB creates a new database with configuration

func SaveWithPrimaryKeys

func SaveWithPrimaryKeys(m Model, keys []string) error

SaveWithPrimaryKeys updates or inserts the provided model in the database, using the provided keys to check if it exists

func UnregisterDB

func UnregisterDB(name string) error

UnregisterDB removes the database from the registry

Types

type DB

type DB interface {
	zesty.DB
	System() DMS
	ExecutorHook() ExecutorHook
	DBSpecific() DBSpecific
}

func GetDB

func GetDB(name string) (DB, error)

GetDB returns a database object from its name

type DBProvider

type DBProvider interface {
	zesty.DBProvider
	EscapeValue(value string) string
	CanSelectForUpdate() bool

	Context() context.Context
	UUID() string

	HasCapacity(capacity DatabaseCapacity) bool
	RunInTransaction(func() error) error
	// contains filtered or unexported methods
}

DBProvider provides an abstracted way of accessing the database

func NewDBProvider

func NewDBProvider(ctx context.Context, name string) (DBProvider, error)

NewDBProvider creates a new db provider

type DBSpecific added in v1.2.0

type DBSpecific interface {
	// OnSessionCreated is a function executed once per DBProvider instance
	OnSessionCreated(DBProvider) error
}

DBSpecific is an interface describing how specificities of each DMS are handled in yaorm

type DMS

type DMS uint8

DMS represents a database management system

const (
	DatabasePostgreSQL DMS = iota ^ 42
	DatabaseMySQL
	DatabaseSqlite3
)

Database management systems.

func (DMS) DriverName

func (d DMS) DriverName() string

DriverName returns the name of the driver for ds.

func (DMS) RekordoValue

func (d DMS) RekordoValue() rekordo.DBMS

RekordoValue returns the rekordo value

type DatabaseCapacity

type DatabaseCapacity int8

DatabaseCapacity describes multiple capacities provided only by some databases systems

type DatabaseConfiguration

type DatabaseConfiguration struct {
	Name             string
	System           DMS
	DSN              string
	MaxOpenConns     int
	MaxIdleConns     int
	ConnMaxLifetime  time.Duration
	ConnMaxIdleTime  time.Duration
	AutoCreateTables bool
	// Dialect database dialect, leave empty for automatic guessing
	Dialect gorp.Dialect
	// ExecutorHook is a configurable hook to add logs, for example, to your sql requests
	ExecutorHook ExecutorHook
	DBSpecific   DBSpecific
}

DatabaseConfiguration configures a database

type DatabaseModel

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

DatabaseModel is the struct every model should compose

func (*DatabaseModel) DBHookBeforeDelete added in v1.1.0

func (dm *DatabaseModel) DBHookBeforeDelete() error

DBHookBeforeDelete is a hook called before performing a DB delete By default, this function does not do anything. If needed, you will have to implement this function in your structure composing this one in order to have your code hook executed

func (*DatabaseModel) DBHookBeforeInsert

func (dm *DatabaseModel) DBHookBeforeInsert() error

DBHookBeforeInsert is a hook called before performing a DB insertion By default, this function does not do anything. If needed, you will have to implement this function in your structure composing this one in order to have your code hook executed

func (*DatabaseModel) DBHookBeforeUpdate

func (dm *DatabaseModel) DBHookBeforeUpdate() error

DBHookBeforeUpdate is a hook called before performing a DB update By default, this function does not do anything. If needed, you will have to implement this function in your structure composing this one in order to have your code hook executed

func (*DatabaseModel) Delete

func (dm *DatabaseModel) Delete() error

Delete removes the model from database In order to be usable, this function needs to be redfined by each composition of this structure

func (*DatabaseModel) GetDBP

func (dm *DatabaseModel) GetDBP() DBProvider

GetDBP should return the DBProvider tied to this model

func (*DatabaseModel) Load

func (dm *DatabaseModel) Load(dbp DBProvider) error

Load loads the model from database given the current struct In order to be usable, this function needs to be redfined by each composition of this structure

func (*DatabaseModel) Save

func (dm *DatabaseModel) Save() error

Save allows saving the model In order to be usable, this function needs to be redfined by each composition of this structure

func (*DatabaseModel) SetDBP

func (dm *DatabaseModel) SetDBP(dbp DBProvider)

SetDBP allows setting a DBProvider to the model, then returned by GetDBP

type DefaultExecutorHook

type DefaultExecutorHook struct{}

DefaultExecutorHook is the default executor hook, returned if no hook has been defined This struct can be composed by any of your executor hooks to avoid having to define every handler

func (DefaultExecutorHook) AfterDelete

func (h DefaultExecutorHook) AfterDelete(ctx context.Context, query string, args ...interface{})

AfterDelete is a hook executed before performing a Delete action on gorp sql executor

func (DefaultExecutorHook) AfterExec added in v1.2.0

func (h DefaultExecutorHook) AfterExec(ctx context.Context, query string, args ...interface{})

AfterExec is a hook executed before performing an Exec action on gorp sql executor

func (DefaultExecutorHook) AfterInsert

func (h DefaultExecutorHook) AfterInsert(ctx context.Context, query string, args ...interface{})

AfterInsert is a hook executed before performing an Insert action on gorp sql executor

func (DefaultExecutorHook) AfterSelect

func (h DefaultExecutorHook) AfterSelect(ctx context.Context, query string, args ...interface{})

AfterSelect is a hook executed before performing a Select action on gorp sql executor

func (DefaultExecutorHook) AfterSelectOne

func (h DefaultExecutorHook) AfterSelectOne(ctx context.Context, query string, args ...interface{})

AfterSelectOne is a hook executed before performing a SelectOne action on gorp sql executor

func (DefaultExecutorHook) AfterUpdate

func (h DefaultExecutorHook) AfterUpdate(ctx context.Context, query string, args ...interface{})

AfterUpdate is a hook executed before performing an Update action on gorp sql executor

func (DefaultExecutorHook) BeforeDelete

func (h DefaultExecutorHook) BeforeDelete(ctx context.Context, query string, args ...interface{})

BeforeDelete is a hook executed before performing a Delete action on gorp sql executor

func (DefaultExecutorHook) BeforeExec added in v1.2.0

func (h DefaultExecutorHook) BeforeExec(ctx context.Context, query string, args ...interface{})

BeforeExec is a hook executed before performing an Exec action on gorp sql executor

func (DefaultExecutorHook) BeforeInsert

func (h DefaultExecutorHook) BeforeInsert(ctx context.Context, query string, args ...interface{})

BeforeInsert is a hook executed before performing an Insert action on gorp sql executor

func (DefaultExecutorHook) BeforeSelect

func (h DefaultExecutorHook) BeforeSelect(ctx context.Context, query string, args ...interface{})

BeforeSelect is a hook executed before performing a Select action on gorp sql executor

func (DefaultExecutorHook) BeforeSelectOne

func (h DefaultExecutorHook) BeforeSelectOne(ctx context.Context, query string, args ...interface{})

BeforeSelectOne is a hook executed before performing a SelectOne action on gorp sql executor

func (DefaultExecutorHook) BeforeUpdate

func (h DefaultExecutorHook) BeforeUpdate(ctx context.Context, query string, args ...interface{})

BeforeUpdate is a hook executed before performing an Update action on gorp sql executor

type ExecutorHook

type ExecutorHook interface {
	BeforeSelectOne(ctx context.Context, query string, args ...interface{})
	AfterSelectOne(ctx context.Context, query string, args ...interface{})
	BeforeSelect(ctx context.Context, query string, args ...interface{})
	AfterSelect(ctx context.Context, query string, args ...interface{})
	BeforeInsert(ctx context.Context, query string, args ...interface{})
	AfterInsert(ctx context.Context, query string, args ...interface{})
	BeforeUpdate(ctx context.Context, query string, args ...interface{})
	AfterUpdate(ctx context.Context, query string, args ...interface{})
	BeforeDelete(ctx context.Context, query string, args ...interface{})
	AfterDelete(ctx context.Context, query string, args ...interface{})
	BeforeExec(ctx context.Context, query string, args ...interface{})
	AfterExec(ctx context.Context, query string, args ...interface{})
}

ExecutorHook can be implemented and set on the database handler Before every query, a new object will be created to provide a way to perform operations, like logging / timing your sql queries

type Model

type Model interface {
	// GetDBP should return the DBProvider tied to this model
	GetDBP() DBProvider
	// SetDBP allows setting a DBProvider to the model, then returned by GetDBP
	SetDBP(dbp DBProvider)
	// Save allows saving the model
	Save() error
	// Load loads the model from database given the current struct
	Load(dbp DBProvider) error
	// Delete removes the model from database
	Delete() error
	// DBHookBeforeInsert is a hook called before performing a DB insertion
	DBHookBeforeInsert() error
	// DBHookBeforeUpdate is a hook called before performing a DB update
	DBHookBeforeUpdate() error
	// DBHookBeforeDelete is a hook called before performing a DB delete
	DBHookBeforeDelete() error
}

Model is the interface every model should implement from

func GenericSelectAll

func GenericSelectAll(dbp DBProvider, filter yaormfilter.Filter) ([]Model, error)

GenericSelectAll selects all rows in the database panics if filter or dbp is nil

func GenericSelectOne

func GenericSelectOne(dbp DBProvider, filter yaormfilter.Filter) (Model, error)

GenericSelectOne selects one row in the database panics if filter or dbp is nil

type PostgresSpecific added in v1.2.0

type PostgresSpecific struct {
	// IntervaStyle holds the style of output of the interval
	// See Postgres manual 8.5.5
	IntervalStyle string
}

PostgresSpecific holds specific configurations used by Postgres

func (PostgresSpecific) OnSessionCreated added in v1.2.0

func (p PostgresSpecific) OnSessionCreated(dbp DBProvider) error

OnSessionCreated is executed when a Session is created. This function will use the: - IntervalStyle

type SqlExecutor

type SqlExecutor struct {
	gorp.SqlExecutor
	// contains filtered or unexported fields
}

SqlExecutor is a custom SQL Executor, on top of the one provided by gorp used to provide multiple hooks before executing statements

func (*SqlExecutor) Delete

func (e *SqlExecutor) Delete(list ...interface{}) (int64, error)

Delete is a handler to delete a list of models from the database

func (*SqlExecutor) Exec added in v1.2.0

func (e *SqlExecutor) Exec(query string, args ...interface{}) (sql.Result, error)

Exec is a handler to execute a SQL query

func (*SqlExecutor) Insert

func (e *SqlExecutor) Insert(list ...interface{}) error

Insert is a handler to insert a list of models inside the database

func (*SqlExecutor) Select

func (e *SqlExecutor) Select(i interface{}, query string, args ...interface{}) ([]interface{}, error)

Select is a handler to select multiple rows from database and return them

func (*SqlExecutor) SelectOne

func (e *SqlExecutor) SelectOne(holder interface{}, query string, args ...interface{}) error

SelectOne is a handler to select only 1 row from database and store it inside the first argument

func (*SqlExecutor) Update

func (e *SqlExecutor) Update(list ...interface{}) (int64, error)

Update is a handler to update a list of models inside the database

type SubqueryloadFunc

type SubqueryloadFunc func(dbp DBProvider, ids []interface{}) (interface{}, error)

type Table

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

Table is the type hosting all the table characteristics

func GetTable

func GetTable(dbName, tableName string) (*Table, error)

GetTable returns the table matching the parameters

func GetTableByFilter

func GetTableByFilter(f yaormfilter.Filter) (*Table, error)

GetTableByFilter returns the table using this filter

func GetTableByModel

func GetTableByModel(m Model) (*Table, error)

GetTableByModel returns the table registered for this model

func NewTable

func NewTable(dbName, tableName string, model Model) *Table

NewTable registers a new table

func (Table) FieldIndex

func (t Table) FieldIndex(field string) int

func (Table) Fields

func (t Table) Fields() []string

func (Table) FieldsWithoutPK

func (t Table) FieldsWithoutPK() []string

func (Table) FilterFieldIndex

func (t Table) FilterFieldIndex(field string) int

func (Table) KeyFields

func (t Table) KeyFields() map[string]int

func (Table) Keys

func (t Table) Keys() []string

func (Table) Name

func (t Table) Name() string

func (Table) NameForQuery

func (t Table) NameForQuery(dbp DBProvider) string

NameForQuery returns the name that should be used for SQL queries

func (Table) NewFilter

func (t Table) NewFilter() (yaormfilter.Filter, error)

func (Table) NewModel

func (t Table) NewModel() (Model, error)

func (Table) NewSlice

func (t Table) NewSlice() (interface{}, error)

func (Table) NewSlicePtr

func (t Table) NewSlicePtr() (interface{}, error)

func (*Table) WithAutoIncrement

func (t *Table) WithAutoIncrement(v bool) *Table

func (*Table) WithFilter

func (t *Table) WithFilter(f yaormfilter.Filter) *Table

func (*Table) WithKeys

func (t *Table) WithKeys(keys []string) *Table

func (*Table) WithSchema

func (t *Table) WithSchema(schema string) *Table

func (*Table) WithSubqueryloading

func (t *Table) WithSubqueryloading(fn SubqueryloadFunc, mapperField string) *Table

type TypeConverter

type TypeConverter struct{}

TypeConverter defines conversion from db to golang

func (TypeConverter) FromDb

func (tc TypeConverter) FromDb(target interface{}) (gorp.CustomScanner, bool)

FromDb converts to golang

func (TypeConverter) ToDb

func (tc TypeConverter) ToDb(val interface{}) (interface{}, error)

ToDb converts to database

Directories

Path Synopsis
_vendor
github.com/lann/builder
Package builder provides a method for writing fluent immutable builders.
Package builder provides a method for writing fluent immutable builders.
github.com/lann/ps
Fully persistent data structures.
Fully persistent data structures.
github.com/lann/squirrel
Package squirrel provides a fluent SQL generator.
Package squirrel provides a fluent SQL generator.
github.com/loopfz/gadgeto/zesty
zesty is based on gorp, and abstracts DB transaction specifics.
zesty is based on gorp, and abstracts DB transaction specifics.
github.com/satori/go.uuid
Package uuid provides implementation of Universally Unique Identifier (UUID).
Package uuid provides implementation of Universally Unique Identifier (UUID).

Jump to

Keyboard shortcuts

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