lorm

package module
v0.17.2 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2022 License: MIT Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

lorm

Django ispired ORM.

Install

go get -u github.com/tada-team/lorm

Setup database

package main

import (
    "database/sql"
    "github.com/tada-team/lorm"
)

func init() {
    connStr := "dbname=... user=... password=... host=... port=... sslmode=..."
    conn, err := sql.Open("postgres", connStr)
    if err != nil {
        panic(err)
    }
    lorm.SetConn(conn)
}

Django models

  1. install django app: https://github.com/tada-team/lorm_exporter
  2. generate models.go from your django models

Examples

Single object

Django:

try:
    user = User.objects.get(id=42)
except User.DoesNotExist:
    raise Exception("user not found")

user.is_archive = False
user.save()

user.delete()

lorm:

user := UserTable.MustGet(42) // same as UserTable.Filter().Id(42).MustGet() 
if user == nil {
    panic("user not found")
}

user.IsArchive = false
if err := user.Save(); err != nil {
    panic(err)
}

if err := user.Delete(); err != nil {
    panic(err)
}

Filter

Django:

for user in User.objects.filter(is_admin=False, created__gt=dt):
    print(user.login)

lorm:

for _, user := range UserTable.Filter().IsAdmin(false).CreatedGt(dt).MustList() {
    fmt.Println(user.login)
}

Low-level queries

package main

import (
    "github.com/tada-team/lorm"
    "github.com/tada-team/lorm/op"
)

func ExampleQuery(i, j int) (int, error) {
    args := op.NewArgs()
    query := op.RawQuery("SELECT", args.Next(i), "*", args.Next(j))
    
    var res int    
    err := lorm.TxScan(nil, query, args, &res)

    return res, err
}

args and query in example above equals to:

args := op.Args{i, j}
query := "SELECT $1 * $2"

RawQuery() works like fmt.Splintln().

API

Supported 3 base functions for database access:

  • lorm.TxExec(tx *lorm.Tx, q op.Query, args op.Args) (sql.Result, error)
  • lorm.TxQuery(tx *lorm.Tx, q op.Query, args op.Args, each func(*sql.Rows) error) error
  • lorm.TxScan(tx *lorm.Tx, q op.Query, args op.Args, dest ...interface{}) error
Query constructor

github.com/tada-team/lorm/op has many helpers. For example:

  • op.Select()
  • op.Delete()
  • op.Insert()
  • op.Or()
  • op.And()
  • op.Not()
  • etc. Try autocomplete.
args := op.NewArgs()
query := op.Select(
    UserTable.Id(),
    UserTable.Created(),
).From(
    UserTable,
).OrderBy(
    UserTable.Created(),
).Where( // .Where() arguments concatenated with "AND" statement
    UserTable.Created().Gt(args.Next(time.Now().Add(-time.Hour))),
    op.Or(
        UserTable.IsArchive(),        
        op.Not(UserTable.IsAdmin()),
        UserTable.GroupId().InSubquery( // wow, subqueries!
            op.Select(
                GroupTable.Id(),
            ).From(
                GroupTable,
            ).Where(
                // HasPrefix is shortcut for "...%"
                GroupTable.Title().ILike(args.Next(op.HasPrefix("aaaaa"))),
            ),
        ),
    ),
).Limit(
    args.Next(10),
)
args := op.NewArgs()
query := op.Insert(t, op.Set{
    op.Column("date"): op.Raw("CURRENT_DATE"),
    op.Column("value"): args.Next(1),
}, op.Set{
    op.Column("date"): op.Raw("CURRENT_DATE"),
    op.Column("value"): args.Next(2),
})
Transactions
package main

import (
    "github.com/tada-team/lorm"
    "github.com/tada-team/lorm/op"
)

func ExampleTransaction(i, j int) (int, error) {
    args := op.NewArgs()
    query := op.RawQuery("SELECT", args.Next(i), "*", args.Next(j))
    
    var res int    
    if err := lorm.Atomic(func(tx *lorm.Tx) error {
        return lorm.TxScan(tx, query, args, &res)    	
    }); err != nil {
        return res, err
    }

    return res, nil
} 
Internal naming
  • r — record (row in database)
  • l – list of records
  • t — table
  • f – filter
  • q — query

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	NonFatalErrors []string
	ShowSql        bool
	MaxAttempts    = 10
)
View Source
var ReloadError = errors.New("lorm: reload error")

Functions

func AfterQuery added in v0.1.2

func AfterQuery(fn afterQueryHandler)

func Atomic added in v0.1.2

func Atomic(fn func(tx *Tx) error) error

func BeforeQuery added in v0.1.2

func BeforeQuery(fn beforeQueryHandler)

func CacheUsed added in v0.6.0

func CacheUsed(name string)

func CachedSelect added in v0.5.0

func CachedSelect(t op.Table) *op.SelectQuery

func DisableLocks added in v0.12.3

func DisableLocks()

func DoCount

func DoCount(f Filter, table op.Table) int

func DoDelete

func DoDelete(r Record, t op.Table) error

func DoDeleteFiltered

func DoDeleteFiltered(f Filter, table op.Table) error

func DoExists

func DoExists(f Filter, table op.Table) bool

func DoGet

func DoGet(f Filter, r Record, t op.Table) (bool, error)

func DoInTx added in v0.9.3

func DoInTx(r Record, fn func() error) error

func DoInsert added in v0.1.13

func DoInsert(r Record, t op.Table) error

func DoPks added in v0.17.0

func DoPks[PK iPK, R interface{ Pk() PK }](l []R) []PK

func DoReload

func DoReload(r Record, t op.Table) error

func DoSave added in v0.8.0

func DoSave(r Record, t op.Table) error

func DoSetListTx added in v0.10.0

func DoSetListTx(tx *Tx, l List)

func DoUpdate added in v0.1.13

func DoUpdate(r Record, t op.Table) error

func EnableLocks added in v0.12.3

func EnableLocks()

func IsCancelingStatementDueToLockTimeout added in v0.15.0

func IsCancelingStatementDueToLockTimeout(err error) bool

func IsDeadlockDetected added in v0.15.0

func IsDeadlockDetected(err error) bool

func IsDuplicateKeyViolatesUniqueConstraint added in v0.15.0

func IsDuplicateKeyViolatesUniqueConstraint(err error) bool

func IsViolatesForeignKeyConstraint added in v0.15.0

func IsViolatesForeignKeyConstraint(err error) bool

func MaybeAddToTx added in v0.1.2

func MaybeAddToTx(tx *Tx, t Transactional)

func MustHavePk added in v0.3.1

func MustHavePk(r HasPk)

func OnCacheUsed added in v0.6.0

func OnCacheUsed(fn cacheUsedHandler)

func QueryCounter added in v0.1.2

func QueryCounter() int64

func SetConn added in v0.1.4

func SetConn(v *sql.DB)

func SetDbParam added in v0.13.0

func SetDbParam(tx *Tx, arg, value string) (err error)

func TxExec added in v0.1.2

func TxExec(tx *Tx, locker sync.Locker, q op.Query, args op.Args) (res sql.Result, err error)

func TxLock2 added in v0.1.2

func TxLock2(tx *Tx, k1, k2 int) error

func TxQuery added in v0.1.2

func TxQuery(tx *Tx, q op.Query, args op.Args, each func(*sql.Rows) error) error

func TxScan added in v0.1.2

func TxScan(tx *Tx, locker sync.Locker, q op.Query, args op.Args, dest ...interface{}) error

func UUID added in v0.12.0

func UUID() string

Types

type BaseCache

type BaseCache struct {
	sync.RWMutex
	Name string
}

type BaseFilter

type BaseFilter struct {
	BaseTransactional
	Conds op.Conds
	Args  op.Args
	// contains filtered or unexported fields
}

func (*BaseFilter) C added in v0.10.1

func (f *BaseFilter) C(v op.Expr)

C = condition

func (BaseFilter) GetArgs

func (f BaseFilter) GetArgs() op.Args

func (BaseFilter) GetConds

func (f BaseFilter) GetConds() op.Conds

func (BaseFilter) GetLimit

func (f BaseFilter) GetLimit() int

func (BaseFilter) GetLock

func (f BaseFilter) GetLock() op.Lock

func (BaseFilter) GetOffset added in v0.4.1

func (f BaseFilter) GetOffset() int

func (BaseFilter) GetOrderBy

func (f BaseFilter) GetOrderBy() op.Expr

func (BaseFilter) IsEmpty

func (f BaseFilter) IsEmpty() bool

func (*BaseFilter) N added in v0.10.2

func (f *BaseFilter) N(v interface{}) op.Placeholder

N = next

func (*BaseFilter) NA added in v0.10.2

func (f *BaseFilter) NA(v interface{}) op.ArrayMask

NA = next array

func (*BaseFilter) SetEmpty

func (f *BaseFilter) SetEmpty()

func (*BaseFilter) SetLimit

func (f *BaseFilter) SetLimit(v int)

func (*BaseFilter) SetLock

func (f *BaseFilter) SetLock(tx *Tx, lock op.Lock)

func (*BaseFilter) SetOffset added in v0.4.1

func (f *BaseFilter) SetOffset(v int)

func (*BaseFilter) SetOrderBy

func (f *BaseFilter) SetOrderBy(v op.Expr)

type BaseRecord added in v0.11.0

type BaseRecord struct {
	BaseTransactional
	sync.RWMutex
}

type BaseTable

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

func NewBaseTable

func NewBaseTable(name, aliasSeed string, fields ...string) BaseTable

func (BaseTable) AllFieldsExpr

func (t BaseTable) AllFieldsExpr() op.Expr

func (BaseTable) Column

func (t BaseTable) Column(v string) op.Column

func (BaseTable) GetAlias

func (t BaseTable) GetAlias() string

func (BaseTable) GetAllFields

func (t BaseTable) GetAllFields() []op.Column

func (BaseTable) Pk

func (t BaseTable) Pk() op.Column

func (*BaseTable) SetAlias

func (t *BaseTable) SetAlias(s string)

func (BaseTable) String

func (t BaseTable) String() string

type BaseTransactional added in v0.1.2

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

func (*BaseTransactional) SetTx added in v0.1.2

func (t *BaseTransactional) SetTx(tx *Tx)

func (*BaseTransactional) Tx added in v0.1.2

func (t *BaseTransactional) Tx() *Tx

type BaseUpdater

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

func NewUpdater

func NewUpdater() BaseUpdater

func (*BaseUpdater) Ch

func (u *BaseUpdater) Ch(f op.Column, v interface{})

func (*BaseUpdater) DoSave

func (u *BaseUpdater) DoSave(r Record, t op.Table) error

func (*BaseUpdater) HasChanges

func (u *BaseUpdater) HasChanges() bool

type Deletable

type Deletable interface {
	Delete() error
}

type Filter

type Filter interface {
	Transactional
	GetArgs() op.Args
	GetConds() op.Conds
	IsEmpty() bool
	GetLock() op.Lock
	GetOrderBy() op.Expr
	GetLimit() int
	GetOffset() int
}

type HasPk added in v0.3.1

type HasPk interface {
	HasPk() bool
}

type List added in v0.10.0

type List interface {
	Records() []Record
}

type Record

type Record interface {
	Transactional
	sync.Locker
	fmt.Stringer
	GetAllFields() []interface{}
	HasPk() bool
	PkCond(args *op.Args) op.Expr
	NewPk()
	Save() error
	PreSave() error
	PostSave() error
}

type Reloadable

type Reloadable interface {
	Reload() error
}

type Saveable

type Saveable interface {
	Save() error
}

type Set added in v0.17.0

type Set[PK iPK] map[PK]struct{}

func (Set[PK]) Add added in v0.17.0

func (s Set[PK]) Add(pk PK)

func (Set[PK]) AsList added in v0.17.0

func (s Set[PK]) AsList() []PK

func (Set[PK]) Contains added in v0.17.0

func (s Set[PK]) Contains(pk PK) bool

type Transactional added in v0.1.2

type Transactional interface {
	Tx() *Tx
	SetTx(tx *Tx)
}

type Tx added in v0.1.2

type Tx struct {
	*sql.Tx
	// contains filtered or unexported fields
}

func DoListTx added in v0.10.0

func DoListTx(l List) *Tx

func NewTx added in v0.1.2

func NewTx(tx *sql.Tx, num int64) *Tx

func (*Tx) Add added in v0.1.2

func (tx *Tx) Add(t Transactional)

func (*Tx) OnSuccess added in v0.9.0

func (tx *Tx) OnSuccess(fn func() error) error

func (*Tx) String added in v0.1.2

func (tx *Tx) String() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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