models

package
v0.0.0-...-da20d80 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2016 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ExprSep = "."
)

ExprSep define the expression separation

Variables

This section is empty.

Functions

func AddModifiers

func AddModifiers(rs RecordSet, doc *etree.Document, fieldInfos map[string]*FieldInfo)

AddModifiers adds the modifiers attribute nodes to given xml doc.

func BootStrap

func BootStrap()

BootStrap freezes model, fields and method caches and syncs the database structure with the declared data.

func CreateModel

func CreateModel(name string, options ...Option)

CreateModel creates a new model with the given name Available options are - TRANSIENT_MODEL: each instance of the model will have a limited lifetime in database (used for wizards)

func DBConnect

func DBConnect(driver, connData string)

DBConnect is a wrapper around sqlx.MustConnect It connects to a database using the given driver and connection data.

func DBExecute

func DBExecute(cr *sqlx.Tx, query string, args ...interface{}) sql.Result

DBExecute is a wrapper around sqlx.MustExec It executes a query that returns no row

func DBGet

func DBGet(cr *sqlx.Tx, dest interface{}, query string, args ...interface{})

DBGet is a wrapper around sqlx.Get It gets the value of a single row found by the given query and arguments It panics in case of error

func DBQuery

func DBQuery(cr *sqlx.Tx, query string, args ...interface{}) *sqlx.Rows

DBQuery is a wrapper around sqlx.Queryx It returns a sqlx.Rowsx found by the given query and arguments It panics in case of error

func DeclareMethod

func DeclareMethod(modelName, methodName string, fnct interface{})

DeclareMethod creates a new method (or override it if it exists) on given model name and adds the given fnct as layer for this method. This function must have a RecordSet as first argument.

func ExtendModel

func ExtendModel(name string, structPtrs ...interface{})

ExtendModel extends the model given by its name with the given struct pointers

func FieldsGet

func FieldsGet(rs RecordSet, args FieldsGetArgs) map[string]*FieldInfo

FieldsGet returns the definition of each field. The _inherits'd fields are included. TODO The string, help, and selection (if present) attributes are translated.

func GetFormviewAction

func GetFormviewAction(rs RecordSet) *ir.BaseAction

GetFormviewAction returns an action to open the document. This method is meant to be overridden in addons that want to give specific view ids for example.

func GetFormviewId

func GetFormviewId(rs RecordSet) string

GetFormviewId returns an view id to open the document with. This method is meant to be overridden in addons that want to give specific view ids for example.

func NameGet

func NameGet(rs RecordSet) string

NameGet is the base implementation of the 'NameGet' method which retrieves the human readable name of an object.

func ProcessView

func ProcessView(rs RecordSet, arch string, fieldInfos map[string]*FieldInfo) string

Process view makes all the necessary modifications to the view arch and returns the new xml string.

func Unlink(rs RecordSet) int64

Unlink is the base implementation of the 'Unlink' method which deletes records in the database.

func UpdateFieldNames

func UpdateFieldNames(rs RecordSet, doc *etree.Document)

UpdateFieldNames changes the field names in the view to the column names. If a field name is already column names then it does nothing.

func Write

func Write(rs RecordSet, data interface{}) bool

Write is the base implementation of the 'Write' method which updates records in the database with the given data. Data can be either a struct pointer or a FieldMap.

Types

type BaseModel

type BaseModel struct {
	ID          int64
	CreateDate  time.Time `yep:"type(datetime);nocopy"`
	CreateUid   int64     `yep:"nocopy"`
	WriteDate   time.Time `yep:"type(datetime);compute(ComputeWriteDate);store;depends(ID);nocopy"`
	WriteUid    int64     `yep:"nocopy"`
	DisplayName string    `yep:"compute(ComputeNameGet)"`
}

type BaseTransientModel

type BaseTransientModel struct {
	ID int64 `orm:"column(id)"`
}

type ColumnData

type ColumnData struct {
	ColumnName    string
	DataType      string
	IsNullable    string
	ColumnDefault sql.NullString
}

type Condition

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

Condition struct. work for WHERE conditions.

func NewCondition

func NewCondition() *Condition

NewCondition return new condition struct

func ParseDomain

func ParseDomain(dom Domain) *Condition

ParseDomain gets an Odoo domain and parses it into a RecordSet query Condition. Returns nil if the domain is []

func (Condition) And

func (c Condition) And(expr string, op string, arg interface{}) *Condition

And add expression to condition

func (*Condition) AndCond

func (c *Condition) AndCond(cond *Condition) *Condition

AndCond combine a condition to current condition

func (Condition) AndNot

func (c Condition) AndNot(expr string, op string, arg interface{}) *Condition

AndNot add NOT expression to condition

func (*Condition) IsEmpty

func (c *Condition) IsEmpty() bool

IsEmpty check the condition arguments are empty or not.

func (Condition) Or

func (c Condition) Or(expr string, op string, arg interface{}) *Condition

Or add OR expression to condition

func (*Condition) OrCond

func (c *Condition) OrCond(cond *Condition) *Condition

OrCond combine a OR condition to current condition

func (Condition) OrNot

func (c Condition) OrNot(expr string, op string, arg interface{}) *Condition

OrNot add OR NOT expression to condition

type Date

type Date time.Time

Date type that JSON marshal and unmarshals as "YYYY-MM-DD"

func (Date) IsNull

func (d Date) IsNull() bool

IsNull returns true if the Date is the zero value

func (Date) MarshalJSON

func (d Date) MarshalJSON() ([]byte, error)

MarshalJSON for Date type

func (Date) Value

func (d Date) Value() (driver.Value, error)

Value formats our Date for storing in database Especially handles empty Date.

type DateTime

type DateTime time.Time

DateTime type that JSON marshals and unmarshals as "YYYY-MM-DD HH:MM:SS"

func (DateTime) IsNull

func (d DateTime) IsNull() bool

IsNull returns true if the DateTime is the zero value

func (DateTime) MarshalJSON

func (d DateTime) MarshalJSON() ([]byte, error)

MarshalJSON for Date type

func (DateTime) Value

func (d DateTime) Value() (driver.Value, error)

Value formats our DateTime for storing in database Especially handles empty DateTime.

type Domain

type Domain []interface{}

Domain is a list of search criteria (DomainTerm) in the form of a tuplet (field_name, operator, value). Domain criteria (DomainTerm) can be combined using logical operators in prefix form (DomainPrefixOperator)

type DomainOperator

type DomainOperator string
const (
	OPERATOR_EQUALS        DomainOperator = "="
	OPERATOR_NOT_EQUALS    DomainOperator = "!="
	OPERATOR_GREATER       DomainOperator = ">"
	OPERATOR_GREATER_EQUAL DomainOperator = ">="
	OPERATOR_LOWER         DomainOperator = "<"
	OPERATOR_LOWER_EQUAL   DomainOperator = "<="
	OPERATOR_UNSET_EQUALS  DomainOperator = "=?"
	OPERATOR_LIKE_PATTERN  DomainOperator = "=like"
	OPERATOR_LIKE          DomainOperator = "like"
	OPERATOR_NOT_LIKE      DomainOperator = "not like"
	OPERATOR_ILIKE         DomainOperator = "ilike"
	OPERATOR_NOT_ILIKE     DomainOperator = "not ilike"
	OPERATOR_ILIKE_PATTERN DomainOperator = "=ilike"
	OPERATOR_IN            DomainOperator = "in"
	OPERATOR_NOT_IN        DomainOperator = "not in"
	OPERATOR_CHILD_OF      DomainOperator = "child_of"
)

type DomainPrefixOperator

type DomainPrefixOperator string
const (
	PREFIX_AND DomainPrefixOperator = "&"
	PREFIX_OR  DomainPrefixOperator = "|"
	PREFIX_NOT DomainPrefixOperator = "!"
)

type DomainTerm

type DomainTerm []interface{}

type Environment

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

Environment is a sql transaction, performed by a user with some context data.

func NewEnvironment

func NewEnvironment(uid int64, context ...tools.Context) *Environment

NewEnvironment returns a new Environment with the given parameters in a new DB transaction.

WARNING: Callers to NewEnvironment should ensure to either commit or rollback the returned Environment.Cr() after operation to release the database connection.

func (Environment) Context

func (env Environment) Context() tools.Context

Context returns the Context of the Environment

func (Environment) Cr

func (env Environment) Cr() *sqlx.Tx

Cr return a pointer to the transaction of the Environment

func (Environment) Create

func (env Environment) Create(data interface{}) *RecordSet

Create creates a new record in database from the given data and returns a recordSet Data must be a struct pointer.

func (Environment) Pool

func (env Environment) Pool(tableName string) *RecordSet

Pool returns an empty RecordSet from the given table name string

func (Environment) Sudo

func (env Environment) Sudo(userId ...int64) *Environment

Sudo returns a new Environment with the given userId or the superuser id if not specified

func (Environment) Sync

func (env Environment) Sync(data interface{}, cols ...string) bool

Sync writes the given data to database. data must be a struct pointer that has been originally populated by RecordSet.ReadOne() or in a batch by RecordSet.ReadAll().

func (Environment) Uid

func (env Environment) Uid() int64

Uid returns the user id of the Environment

func (Environment) WithContext

func (env Environment) WithContext(ctx tools.Context, replace ...bool) *Environment

WithContext returns a new Environment with its context updated by ctx. If replace is true, then the context is replaced by the given ctx instead of being updated.

type FieldInfo

type FieldInfo struct {
	ChangeDefault    bool                   `json:"change_default"`
	Help             string                 `json:"help"`
	Searchable       bool                   `json:"searchable"`
	Views            map[string]interface{} `json:"views"`
	Required         bool                   `json:"required"`
	Manual           bool                   `json:"manual"`
	ReadOnly         bool                   `json:"readonly"`
	Depends          []string               `json:"depends"`
	CompanyDependent bool                   `json:"company_dependent"`
	Sortable         bool                   `json:"sortable"`
	Translate        bool                   `json:"translate"`
	Type             tools.FieldType        `json:"type"`
	Store            bool                   `json:"store"`
	String           string                 `json:"string"`
	Domain           Domain                 `json:"domain"`
	Relation         string                 `json:"relation"`
}

Exportable field information struct

type FieldMap

type FieldMap map[string]interface{}

FieldMap is a map of interface{} specifically used for holding model fields values.

func ComputeNameGet

func ComputeNameGet(rs RecordSet) FieldMap

ComputeNameGet updates the DisplayName field with the result of NameGet.

func ComputeWriteDate

func ComputeWriteDate(rs RecordSet) FieldMap

ComputeWriteDate updates the WriteDate field with the current datetime.

func DefaultGet

func DefaultGet(rs RecordSet) FieldMap

DefaultGet returns a Params map with the default values for the model.

func Onchange

func Onchange(rs RecordSet, params OnchangeParams) FieldMap

Onchange returns the values that must be modified in the pseudo-record given as params.Values

func Read

func Read(rs RecordSet, fields []string) []FieldMap

Read is the base implementation of the 'Read' method. It reads the database and returns a list of FieldMap of the given model

func SearchRead

func SearchRead(rs RecordSet, params SearchParams) []FieldMap

SearchRead retrieves database records according to the filters defined in params.

func (FieldMap) Keys

func (fm FieldMap) Keys() (res []string)

Keys returns the FieldMap keys as a slice of strings

func (*FieldMap) SubstituteKeys

func (fm *FieldMap) SubstituteKeys(substs []KeySubstitution)

substituteKeys changes the column names of the given field map with the given substitutions.

func (FieldMap) Values

func (fm FieldMap) Values() (res []interface{})

Values returns the FieldMap values as a slice of interface{}

type FieldsGetArgs

type FieldsGetArgs struct {
	// list of fields to document, all if empty or not provided
	AllFields []string `json:"allfields"`
}

Args for the FieldsGet function

type FieldsViewData

type FieldsViewData struct {
	Name        string                `json:"name"`
	Arch        string                `json:"arch"`
	ViewID      string                `json:"view_id"`
	Model       string                `json:"model"`
	Type        ir.ViewType           `json:"type"`
	Fields      map[string]*FieldInfo `json:"fields"`
	Toolbar     ir.Toolbar            `json:"toolbar"`
	FieldParent string                `json:"field_parent"`
}

Return type string for the FieldsViewGet function

func FieldsViewGet

func FieldsViewGet(rs RecordSet, args FieldsViewGetParams) *FieldsViewData

FieldsViewGet is the base implementation of the 'FieldsViewGet' method which gets the detailed composition of the requested view like fields, model, view architecture.

type FieldsViewGetParams

type FieldsViewGetParams struct {
	ViewID   string `json:"view_id"`
	ViewType string `json:"view_type"`
	Toolbar  bool   `json:"toolbar"`
}

FieldsViewGetParams is the args struct for the FieldsViewGet function

type KeySubstitution

type KeySubstitution struct {
	Orig string
	New  string
	Keep bool
}

KeySubstitution defines a key substitution in a FieldMap

type NameSearchParams

type NameSearchParams struct {
	Args     Domain      `json:"args"`
	Name     string      `json:"name"`
	Operator string      `json:"operator"`
	Limit    interface{} `json:"limit"`
}

NameSearchParams is the args struct for the NameSearch function

type OnchangeParams

type OnchangeParams struct {
	Values   FieldMap          `json:"values"`
	Fields   []string          `json:"field_name"`
	Onchange map[string]string `json:"field_onchange"`
}

type Option

type Option int
const (
	TRANSIENT_MODEL Option = 1 << iota
)

type Query

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

type RecordRef

type RecordRef struct {
	ID   int64
	Name string
}

RecordRef is a tuple with an ID and the display name of a record

func NameSearch

func NameSearch(rs RecordSet, params NameSearchParams) []RecordRef

NameSearch searches for records that have a display name matching the given `name` pattern when compared with the given `operator`, while also matching the optional search domain (`args`).

This is used for example to provide suggestions based on a partial value for a relational field. Sometimes be seen as the inverse function of NameGet but it is not guaranteed to be.

func (RecordRef) MarshalJSON

func (rf RecordRef) MarshalJSON() ([]byte, error)

MarshalJSON for RecordRef type

func (*RecordRef) UnmarshalJSON

func (rf *RecordRef) UnmarshalJSON(data []byte) error

UnmarshalJSON for RecordRef type

type RecordSet

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

RecordSet is a generic struct representing several records of a model.

func Copy

func Copy(rs RecordSet) *RecordSet

Copy duplicates the record given by rs It panics if rs is not a singleton

func Create

func Create(rs RecordSet, data interface{}) *RecordSet

Create is the base implementation of the 'Create' method which creates a record in the database from the given structPtr. Returns a pointer to a RecordSet with the created id.

func (RecordSet) Call

func (rs RecordSet) Call(methName string, args ...interface{}) interface{}

Call calls the given method name methName with the given arguments and return the result as interface{}.

func (RecordSet) Condition

func (rs RecordSet) Condition(cond *Condition) *RecordSet

SetCond returns a new RecordSet with the given additional condition

func (RecordSet) Create

func (rs RecordSet) Create(data interface{}) *RecordSet

Create is a shortcut function for rs.Call("Create") on the current RecordSet. Data can be either a struct pointer or a FieldMap.

func (RecordSet) Distinct

func (rs RecordSet) Distinct() *RecordSet

Distinct returns a new RecordSet with its Query filtering duplicates

func (RecordSet) EnsureOne

func (rs RecordSet) EnsureOne()

EnsureOne panics if rs is not a singleton

func (RecordSet) Env

func (rs RecordSet) Env() *Environment

Env returns the RecordSet's Environment

func (RecordSet) Exclude

func (rs RecordSet) Exclude(cond, op string, data interface{}) *RecordSet

Exclude returns a new RecordSet with the given additional NOT filter condition.

func (RecordSet) Filter

func (rs RecordSet) Filter(cond, op string, data interface{}) *RecordSet

Filter returns a new RecordSet with the given additional filter condition.

func (*RecordSet) ForceSearch

func (rs *RecordSet) ForceSearch() *RecordSet

ForceSearch query the database with the current filter and fills the RecordSet with the queries ids. Overwrite RecordSet Ids if any. It panics in case of error. It returns a pointer to the same RecordSet.

func (RecordSet) GroupBy

func (rs RecordSet) GroupBy(exprs ...string) *RecordSet

GroupBy returns a new RecordSet with the given GROUP BY clause in its Query

func (RecordSet) ID

func (rs RecordSet) ID() int64

ID returns the ID of the unique record of this RecordSet It panics if rs is not a singleton.

func (RecordSet) Ids

func (rs RecordSet) Ids() []int64

Ids returns the ids of the RecordSet

func (RecordSet) Limit

func (rs RecordSet) Limit(limit int, args ...int) *RecordSet

Limit returns a new RecordSet with the given limit as additional condition

func (RecordSet) MethodType

func (rs RecordSet) MethodType(methName string) reflect.Type

MethodType returns the type of the method given by methName

func (RecordSet) ModelName

func (rs RecordSet) ModelName() string

ModelName returns the model name of the RecordSet

func (RecordSet) Offset

func (rs RecordSet) Offset(offset int) *RecordSet

Offset returns a new RecordSet with the given offset as additional condition

func (RecordSet) OrderBy

func (rs RecordSet) OrderBy(exprs ...string) *RecordSet

OrderBy returns a new RecordSet with the given ORDER BY clause in its Query

func (RecordSet) ReadAll

func (rs RecordSet) ReadAll(container interface{}, cols ...string) int64

ReadAll query all data pointed by the RecordSet and map to containers. If cols are given, retrieve only the given fields. Returns the number of rows fetched. It panics in case of error

func (RecordSet) ReadOne

func (rs RecordSet) ReadOne(container interface{}, cols ...string)

ReadOne query the RecordSet row and map to container. If cols are given, retrieve only the given fields. It panics if the RecordSet does not contain exactly one row.

func (RecordSet) ReadValue

func (rs RecordSet) ReadValue(result *FieldMap, fields ...string)

Value query a single line of data in the database and maps the result to the result FieldMap

func (RecordSet) ReadValues

func (rs RecordSet) ReadValues(results *[]FieldMap, fields ...string) int64

Values query all data of the RecordSet and map to []FieldMap. fields are the fields to retrieve in the expression format, i.e. "User.Profile.Age" or "user_id.profile_id.age". If no fields are given, all columns of the RecordSet's model are retrieved.

func (RecordSet) Records

func (rs RecordSet) Records() []*RecordSet

Records returns the slice of RecordSet singletons that constitute this RecordSet

func (RecordSet) RelatedDepth

func (rs RecordSet) RelatedDepth(depth int) *RecordSet

RelatedDepth sets the depth at which to populate the structs with ReadOne and ReadAll.

func (*RecordSet) Search

func (rs *RecordSet) Search() *RecordSet

Search query the database with the current filter and fills the RecordSet with the queries ids. Does nothing in case RecordSet already has Ids. It panics in case of error. It returns a pointer to the same RecordSet.

func (RecordSet) SearchCount

func (rs RecordSet) SearchCount() int

SearchCount fetch from the database the number of records that match the RecordSet conditions It panics in case of error

func (RecordSet) String

func (rs RecordSet) String() string

String returns the string representation of a RecordSet

func (RecordSet) Super

func (rs RecordSet) Super(args ...interface{}) interface{}

Super calls the next method Layer after the given funcPtr. This method is meant to be used inside a method layer function to call its parent.

func (rs RecordSet) Unlink() int64

Unlink is a shortcut for rs.Call("Unlink") on the current RecordSet.

func (RecordSet) Write

func (rs RecordSet) Write(data interface{}) bool

Write is a shortcut for rs.Call("Write") on the current RecordSet. Data can be either a struct pointer or a FieldMap.

type SQLParams

type SQLParams []interface{}

func (SQLParams) Extend

func (p SQLParams) Extend(p2 SQLParams) SQLParams

Extend returns a new SQLParams with both params of this SQLParams and of p2 SQLParams.

type SearchParams

type SearchParams struct {
	Domain Domain      `json:"domain"`
	Fields []string    `json:"fields"`
	Offset int         `json:"offset"`
	Limit  interface{} `json:"limit"`
	Order  string      `json:"order"`
}

Jump to

Keyboard shortcuts

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