refbook

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2022 License: MIT Imports: 9 Imported by: 0

README

refbook GoDoc Build Status Coverage Status Go Report Card

Easy access to database reference tables

Concept

Reference book is a plain table usually used as lookup with following characteristics:

  • table has limited amount of rows
  • new rows are introduced quite seldom
  • primary key is an integer
  • name can be in a single language - TEXT, or multi language - JSONB

Examples

Single Language, Plain Reference Table
  // create table party_types (
  //    id    int4 not null,
  //    name  text not null,
  //    constraint party_types_pk primary key(id)
  // ); 
  // insert into party_types(id, name) values(1, 'Individual'), (2, 'Organization');
  
  db, err := sql.Open("postgres", constr)
  pt := refbook.New().LoadFromSQL(db, "party_types")
  if pt.Err() != nil {
    // 
  }
  fmt.Println(pt.Name(1))     // Individual
  fmt.Println(pt.IsExist(2))  // true
  fmt.Println(pt.Name(3))     // returns var NotFoundName  
Multi Language, Plain Reference Table
  // create table party_types (
  //    id    int4 not null,
  //    name  jsonb not null,
  //    constraint party_types_pk primary key(id)
  // ); 
  // insert into party_types(id, name)  values
  // (1, '{"en" : "Individual", "ru": "Физ.лицо"}'::jsonb), 
  // (2, '{"en" : "Organzation", "ru": "Организация"}'::jsonb);
  //
  // 
  db, err := sql.Open("postgres", constr)
  pt := refbook.NewMLRefBook().LoadFromSQL(db, "party_types")
  if pt.Err() != nil {
    // 
  }
  fmt.Println(pt.Lang("ru").Name(1)) // Физ.лицо"
  fmt.Println(pt.Lang("en").Name(2)) // Organzation"
  fmt.Println(pt.Lang("en").Name(3)) // ? (as default response if key not found)
Single Language, Extended Reference Table
// create table event_types (
//    id          int4 not null,
//    code        text not null,
//    name        text not null,
//    is_critical bool not null default false,
//    constraint event_types_pk primary key(id)
// ); 
// insert into event_types(id, code, name, is_critical) values
// (1, 'CONLOST', 'Connection Lost', true), 
// (2, 'SERVERUP', 'Server up', false);

type EventType struct {
  ID          int
  Code        string
  Name        string
  IsCritical  bool  
}
var ets []EventType
db, err := sql.Open("postgres", constr)
//
// read rows somehow to the slice et
//
et := refbook.New().LoadFromSlice(et, "ID", "Name")

fmt.Println(et.Name(1)) // Individual
fmt.Println(et.Name(3)) // ? (as default response for if key not found)
Multi Language, Extended Reference Table
  // create table event_types (
  //    id          int4 not null,
  //    code        text not null,
  //    name        jsonb not null,
  //    is_critical bool not null default false,
  //    constraint event_types_pk primary key(id)
  // ); 
  // insert into event_types(id, code, name, is_critical) values
  // (1, 'CONLOST', '{"en":"Connection lost", "ru": "Связь потеряна"}'::jsonb, true), 
  // (2, 'SERVERUP', '{"en":"Server up", "ru": "Сервер поднят"}'::jsonb, false);
  
  type EventType struct {
    ID          int
    Code        string
    Name        string
    IsCritical  bool  
  }
  var ets []EventType

  db, err := sql.Open("postgres", constr)
  //
  // read rows somehow to the slice ets
  //
  et := refbook.NewMLRefBook().LoadFromSlice(ets, "ID", "Name")
  
  fmt.Println(et.Lang("ru").Name(1))  // Связь потеряна
  fmt.Println(et.Lang("en").Name(2))  // Server up
  fmt.Println(et.Lang("en").Name(3))  // ? 

  fmt.Println(et.IsExist(2))          // true

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// NotFoundName returns by Name() if key not found.
	NotFoundName = "?"
)

Functions

func SetDefaultLang

func SetDefaultLang(lang string)

SetDefaultLang changes default language.

func WithDefaultLang

func WithDefaultLang(lang string) func(o *Option)

WithDefaultLang replaces global default language.

func WithTablename added in v0.0.2

func WithTablename(tableName string) func(o *Option)

func WithThreadSafe

func WithThreadSafe() func(o *Option)

WithThreadSafe informs that it is changeable book.

Types

type Book

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

Book implements in-memory storage of reference book in a single language.

func NewBook

func NewBook() *Book

NewBook returns new instance of concurrent unsafe Book. Use this function if you does not expect items modification in runtime.

func NewConcurrentBook

func NewConcurrentBook() *Book

NewConcurrentBook returns new instance of concurrent safe Book.

func (*Book) Contains

func (b *Book) Contains(s string, dst *[]int)

Contains adds to dst ID of reference book items if name contains s. The function is case unsensitive.

func (*Book) Hash

func (b *Book) Hash() uint64

Hash returns hash taken out of all items.

func (*Book) IsExist

func (b *Book) IsExist(id int) bool

IsExist return true if item with id exists.

func (*Book) JSON

func (b *Book) JSON() []byte

JSON returns items as JSON array [{"id":1, "name" :"aaaa"},...].

func (*Book) Len

func (b *Book) Len() int

Len returns items count.

func (*Book) LoadFromSlice

func (b *Book) LoadFromSlice(slice interface{}, attrid string, attrname string) error

LoadFromSlice init reference book with id, name pairs from any slice.

func (*Book) MarshalJSON added in v0.0.2

func (b *Book) MarshalJSON() ([]byte, error)

func (*Book) Name

func (b *Book) Name(lc LangCode, id int) string

Name return reference book item's name by id. Returns variable NotFoundName if id is not found.

func (*Book) Optimize

func (b *Book) Optimize() error

Optimize calculates hash and pre-generates JSON.

func (*Book) Parse

func (b *Book) Parse(buf []byte) error

Parse parses JSON array with objects [{"id": 1, "name": "Hello"},..] and inits

func (*Book) Set

func (b *Book) Set(id int, name string)

Set inserts/update reference book item. Does nothing if an item exist.

func (*Book) Traverse

func (b *Book) Traverse(f func(id int, name string) (next bool))

Traverse walks through the reference book items. Calls f() for each element. Aborts traverse if f() return false.

type FlexBook

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

FlexBook implements reference book in-memory storage.

func NewFlexBook

func NewFlexBook(f ...func(*Option)) *FlexBook

NewFlexBook returns new reference book instance.

func (*FlexBook) AddItem

func (b *FlexBook) AddItem(item Item)

AddItem adds item to the book.

func (*FlexBook) AddItems

func (b *FlexBook) AddItems(items []Item)

AddItems adds items to the book.

func (*FlexBook) AddMultiLangItem

func (b *FlexBook) AddMultiLangItem(item MultiLangItem)

AddMultiLangItem adds item to the book.

func (*FlexBook) AddMultiLangItems

func (b *FlexBook) AddMultiLangItems(items []MultiLangItem)

AddMultiLangItems adds multiple items to the book.

func (*FlexBook) Book

func (b *FlexBook) Book(lang string) *Book

Book returns pointer to the reference book associated with lang. Returns pointer to the book associates with default language if lang not found.

func (*FlexBook) BookAsJSON

func (b *FlexBook) BookAsJSON(lang string, dst *[]byte)

func (*FlexBook) Hash

func (b *FlexBook) Hash(lang string) uint64

func (*FlexBook) IsExist

func (b *FlexBook) IsExist(id int) bool

IsExist returns true.

func (*FlexBook) Len

func (b *FlexBook) Len() int

Len returns reference book length.

func (*FlexBook) LoadFromSlice

func (b *FlexBook) LoadFromSlice(src interface{}, attrid string, attrname string) error

func (*FlexBook) Name

func (b *FlexBook) Name(lc LangCode, id int) string

Name return name by id.

func (*FlexBook) Optimize added in v0.0.2

func (b *FlexBook) Optimize() error

func (*FlexBook) Parse

func (b *FlexBook) Parse(src []byte) error

Parse recognizes input JSON presented as [{"id": 1, "name" : "Hello"},..] or [{"id":1, "name":{"en":"Hello","ru":"Привет"}},...] or mix [{"id":1, "name":"Hello"}, {"id":2, "name":{"en":"World", "ru":"Мир"}},...]

func (*FlexBook) SetThreadSafe

func (b *FlexBook) SetThreadSafe()

SetThreadSafe sets flag what wraps access to internals by mutex.

func (*FlexBook) TableName added in v0.0.2

func (b *FlexBook) TableName() string

type Item

type Item struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
}

Item describes JSON unmarshal destination for single language reference table.

type LangCode

type LangCode uint16

func ToLangCode

func ToLangCode(src string) LangCode

type MultiLangItem

type MultiLangItem struct {
	ID   int               `json:"id"`
	Name map[string]string `json:"name"`
}

MultiLangItem describes JSON unmarshal destination for multi language reference table.

type Option

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

Option holds FlexBook configuration.

Jump to

Keyboard shortcuts

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