skydb

package
v0.15.0 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	Ascending SortOrder = iota
	Descending
	Asc  = Ascending
	Desc = Descending
)

A list of SordOrder, their meaning is self descriptive.

View Source
const (
	ReadLevel   ACLLevel = "read"
	WriteLevel           = "write"
	CreateLevel          = "create"
)

ReadLevel and WriteLevel is self-explanatory

Variables

View Source
var EmptyRows = NewRows(emptyRowsIter(0))

EmptyRows is a convenient variable that acts as an empty Rows. Useful for skydb implementators and testing.

View Source
var ErrDatabaseIsReadOnly = errors.New("skydb: database is read only")

ErrDatabaseIsReadOnly is returned by skydb.Database if the requested operation modifies the database and the database is readonly.

View Source
var ErrDatabaseTxDidBegin = errors.New("skydb: a transaction has already begun")
View Source
var ErrDatabaseTxDidNotBegin = errors.New("skydb: a transaction has not begun")
View Source
var ErrDatabaseTxDone = errors.New("skydb: Database's transaction has already commited or rolled back")
View Source
var ErrDeviceNotFound = errors.New("skydb: Specific device not found")

ErrDeviceNotFound is returned by Conn.GetDevice, Conn.DeleteDevice, Conn.DeleteDevicesByToken and Conn.DeleteEmptyDevicesByTime, if the desired Device cannot be found in the current container

View Source
var ErrRecordNotFound = errors.New("skydb: Record not found for the specified key")

ErrRecordNotFound is returned from Get and Delete when Database cannot find the Record by the specified key

View Source
var ErrRoleUpdatesFailed = errors.New("skydb: Update of user roles failed")
View Source
var ErrSubscriptionNotFound = errors.New("skydb: Subscription ID not found")

ErrSubscriptionNotFound is returned from GetSubscription or DeleteSubscription when the specific subscription cannot be found.

View Source
var ErrUserDuplicated = errors.New("skydb: duplicated UserID or Username")

ErrUserDuplicated is returned by Conn.CreateUser when the UserInfo to be created has the same ID/username in the current container

View Source
var ErrUserNotFound = errors.New("skydb: UserInfo ID not found")

ErrUserNotFound is returned by Conn.GetUser, Conn.UpdateUser and Conn.DeleteUser when the UserInfo's ID is not found in the current container

View Source
var PublicDatabaseIdentifier = "_public"
View Source
var UnionDatabaseIdentifier = "_union"
View Source
var ZeroTime = time.Time{}

ZeroTime represent a zero time.Time. It is used in DeleteDevicesByToken and DeleteEmptyDevicesByTime to signify a Delete without time constraint.

Functions

func Register

func Register(name string, driver Driver)

Register makes an Skygear Server database driver available with the given name.

Register panics if it is called with a nil driver or the same driver name is being registered twice.

Types

type ACLLevel

type ACLLevel string

ACLLevel represent the operation a user granted on a resource

type APSSetting

type APSSetting struct {
	Alert                      *AppleAlert `json:"alert,omitempty"`
	SoundName                  string      `json:"sound,omitempty"`
	ShouldBadge                bool        `json:"should-badge,omitempty"`
	ShouldSendContentAvailable bool        `json:"should-send-content-available,omitempty"`
}

APSSetting describes how server should send a notification to a targeted device via Apple Push Service.

type AccessModel added in v0.4.0

type AccessModel int

AccessModel indicates the type of access control model while db query.

const (
	RoleBasedAccess AccessModel = iota + 1
	RelationBasedAccess
)

RoleBasedAccess is tranditional Role based Access Control RelationBasedAccess is Access Control determine by the user-user relation between creator and accessor

func GetAccessModel added in v0.4.0

func GetAccessModel(accessString string) AccessModel

GetAccessModel convert the string config to internal const

func (AccessModel) String added in v0.6.0

func (i AccessModel) String() string

type AppleAlert

type AppleAlert struct {
	Body                  string   `json:"body,omitempty"`
	LocalizationKey       string   `json:"loc-key,omitempty"`
	LocalizationArgs      []string `json:"loc-args,omitempty"`
	LaunchImage           string   `json:"launch-image,omitempty"`
	ActionLocalizationKey string   `json:"action-loc-key,omitempty"`
}

AppleAlert describes how a remote notification behaves and shows itself when received.

It is a subset of attributes defined in Apple's "Local and Remote Notification Programming Guide". Please follow the following link for detailed description of the attributes.

https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html#//apple_ref/doc/uid/TP40008194-CH100-SW20

type Asset

type Asset struct {
	Name        string
	ContentType string
	Size        int64
	Public      bool
	Signer      asset.URLSigner
}

func (*Asset) SignedURL

func (a *Asset) SignedURL() string

SignedURL will try to return a signedURL with the injected Signer.

type AuthInfo

type AuthInfo map[string]map[string]interface{}

AuthInfo represents the dictionary of authenticated principal ID => authData.

For example, a UserInfo connected with a Facebook account might look like this:

{
  "com.facebook:46709394": {
    "accessToken": "someAccessToken",
    "expiredAt": "2015-02-26T20:05:48",
    "facebookID": "46709394"
  }
}

It is assumed that the Facebook AuthProvider has "com.facebook" as provider name and "46709394" as the authenticated Facebook account ID.

type Conn

type Conn interface {

	// CreateUser creates a new UserInfo in the container
	// this Conn associated to.
	CreateUser(userinfo *UserInfo) error

	// GetUser fetches the UserInfo with supplied ID in the container and
	// fills in the supplied UserInfo with the result.
	//
	// GetUser returns ErrUserNotFound if no UserInfo exists
	// for the supplied ID.
	GetUser(id string, userinfo *UserInfo) error

	// GetUserByUsernameEmail fetch the UserInfo with supplied username or email,
	//
	GetUserByUsernameEmail(username string, email string, userinfo *UserInfo) error

	// GetUserByPrincipalID fetches the UserInfo with supplied principal ID in the
	// container and fills in the supplied UserInfo with the result.
	//
	// Principal ID is an ID of an authenticated principal with such
	// authentication provided by AuthProvider.
	//
	// GetUserByPrincipalID returns ErrUserNotFound if no UserInfo exists
	// for the supplied principal ID.
	GetUserByPrincipalID(principalID string, userinfo *UserInfo) error

	// UpdateUser updates an existing UserInfo matched by the ID field.
	//
	// UpdateUser returns ErrUserNotFound if such UserInfo does not
	// exist in the container.
	UpdateUser(userinfo *UserInfo) error

	// QueryUser queries for UserInfo matching one of the specified emails.
	QueryUser(emails []string, usernames []string) ([]UserInfo, error)

	// DeleteUser removes UserInfo with the supplied ID in the container.
	//
	// DeleteUser returns ErrUserNotFound if such UserInfo does not
	// exist in the container.
	DeleteUser(id string) error

	// GetAdminRoles return the current admine roles
	GetAdminRoles() ([]string, error)

	// SetAdminRoles accepts array of role, the order will be
	SetAdminRoles(roles []string) error

	// GetDefaultRoles return the current default roles
	GetDefaultRoles() ([]string, error)

	// SetDefaultRoles accepts array of roles, the supplied roles will assigned
	// to newly created user CreateUser
	SetDefaultRoles(roles []string) error

	// SetRecordAccess sets default record access of a specific type
	SetRecordAccess(recordType string, acl RecordACL) error

	// GetRecordAccess returns default record access of a specific type
	GetRecordAccess(recordType string) (RecordACL, error)

	// GetAsset retrieves Asset information by its name
	GetAsset(name string, asset *Asset) error

	// SaveAsset saves an Asset information into a container to
	// be referenced by records.
	SaveAsset(asset *Asset) error

	QueryRelation(user string, name string, direction string, config QueryConfig) []UserInfo
	QueryRelationCount(user string, name string, direction string) (uint64, error)
	AddRelation(user string, name string, targetUser string) error
	RemoveRelation(user string, name string, targetUser string) error

	GetDevice(id string, device *Device) error

	// QueryDevicesByUser queries the Device database which are registered
	// by the specified user.
	QueryDevicesByUser(user string) ([]Device, error)
	SaveDevice(device *Device) error
	DeleteDevice(id string) error

	// DeleteDevicesByToken deletes device where its Token == token and
	// LastRegisteredAt < t. If t == ZeroTime, LastRegisteredAt is not considered.
	//
	// If such device does not exist, ErrDeviceNotFound is returned.
	DeleteDevicesByToken(token string, t time.Time) error

	// DeleteEmptyDevicesByTime deletes device where Token is empty and
	// LastRegisteredAt < t. If t == ZeroTime, LastRegisteredAt is not considered.
	//
	// If such device does not exist, ErrDeviceNotFound is returned.
	DeleteEmptyDevicesByTime(t time.Time) error

	PublicDB() Database
	PrivateDB(userKey string) Database
	UnionDB() Database

	// Subscribe registers the specified recordEventChan to receive
	// RecordEvent from the Conn implementation
	Subscribe(recordEventChan chan RecordEvent) error

	Close() error
}

Conn encapsulates the interface of an Skygear Server connection to a container.

func Open

func Open(implName string, appName string, accessString string, optionString string, migrate bool) (Conn, error)

Open returns an implementation of Conn to use w.r.t implName.

optionString is passed to the driver and is implementation specific. For example, in a SQL implementation it will be something like "sql://localhost/db0"

type CountFunc

type CountFunc struct {
	OverallRecords bool
}

CountFunc represents a function that count number of rows matching a query

func (CountFunc) Args

func (f CountFunc) Args() []interface{}

Args implements the Func interface

type DBHookFunc

type DBHookFunc func(Database, *Record, RecordHookEvent)

DBHookFunc specifies the interface of a database hook function

type Data

type Data map[string]interface{}

A Data represents a key-value object used for storing ODRecord.

type DataType

type DataType uint

DataType defines the type of data that can saved into an skydb database

const (
	TypeString DataType = iota + 1
	TypeNumber
	TypeBoolean
	TypeJSON
	TypeReference
	TypeLocation
	TypeDateTime
	TypeAsset
	TypeACL
	TypeInteger
	TypeSequence
)

List of persistable data types in skydb

func (DataType) IsNumberCompatibleType added in v0.11.0

func (t DataType) IsNumberCompatibleType() bool

IsNumberCompatibleType returns true if the type is a numeric type

func (DataType) String added in v0.6.0

func (i DataType) String() string

type Database

type Database interface {

	// Conn returns the parent Conn of the Database
	Conn() Conn

	// ID returns the identifier of the Database.
	// We have public and private database. For public DB, the ID is
	// `_public`; for union DB, the ID is `_union`;
	// for private, the ID is the user identifier
	ID() string

	// DatabaseType returns the DatabaseType of the database.
	DatabaseType() DatabaseType

	// UserRecordType returns name of the user record type.
	UserRecordType() string

	// IsReadOnly returns true if the database is read only
	IsReadOnly() bool

	// Get fetches the Record identified by the supplied key and
	// writes it onto the supplied Record.
	//
	// Get returns an ErrRecordNotFound if Record identified by
	// the supplied key does not exist in the Database.
	// It also returns error if the underlying implementation
	// failed to read the Record.
	Get(id RecordID, record *Record) error
	GetByIDs(ids []RecordID) (*Rows, error)

	// Save updates the supplied Record in the Database if Record with
	// the same key exists, else such Record is created.
	//
	// Save returns an error if the underlying implemention failed to
	// create / modify the Record.
	Save(record *Record) error

	// Delete removes the Record identified by the key in the Database.
	//
	// Delete returns an ErrRecordNotFound if the Record identified by
	// the supplied key does not exist in the Database.
	// It also returns an error if the underlying implementation
	// failed to remove the Record.
	Delete(id RecordID) error

	// Query executes the supplied query against the Database and returns
	// an Rows to iterate the results.
	Query(query *Query) (*Rows, error)

	// QueryCount executes the supplied query against the Database and returns
	// the number of records matching the query's predicate.
	QueryCount(query *Query) (uint64, error)

	// Extend extends the Database record schema such that a record
	// arrived subsequently with that schema can be saved
	//
	// Extend returns an error if the specified schema conflicts with
	// existing schem in the Database
	Extend(recordType string, schema RecordSchema) error

	// RenameSchema renames a column of the Database record schema
	RenameSchema(recordType, oldColumnName, newColumnName string) error

	// DeleteSchema removes a column of the Database record schema
	DeleteSchema(recordType, columnName string) error

	// GetSchema returns the record schema of a record type
	GetSchema(recordType string) (RecordSchema, error)

	// FetchRecordTypes returns a list of all existing record type
	GetRecordSchemas() (map[string]RecordSchema, error)

	GetSubscription(key string, deviceID string, subscription *Subscription) error
	SaveSubscription(subscription *Subscription) error
	DeleteSubscription(key string, deviceID string) error
	GetSubscriptionsByDeviceID(deviceID string) []Subscription
	GetMatchingSubscriptions(record *Record) []Subscription
}

Database represents a collection of record (either public or private) in a container.

type DatabaseType added in v0.13.0

type DatabaseType int
const (
	// PublicDatabase is a database containing records shared among all
	// users. ACL settings may apply to restrict accesss.
	PublicDatabase DatabaseType = 0 + iota

	// PrivateDatabase is a database containing records visible to
	// an individual user. Each individual user has their own private
	// database. ACL settings do not apply.
	PrivateDatabase

	// UnionDatabase is a database containing all records in the PublicDatabase
	// and all PrivateDatabase. This database is only intended for admin
	// user and ACL settings do not apply.
	UnionDatabase
)

type Device

type Device struct {
	ID               string
	Type             string
	Token            string
	UserInfoID       string
	LastRegisteredAt time.Time
}

Device represents a device owned by a user and ready to receive notification.

type DistanceFunc

type DistanceFunc struct {
	Field    string
	Location Location
}

DistanceFunc represents a function that calculates distance between a user supplied location and a Record's field

func (DistanceFunc) Args

func (f DistanceFunc) Args() []interface{}

Args implements the Func interface

type Driver

type Driver interface {
	Open(appName string, accessModel AccessModel, optionString string, migrate bool) (Conn, error)
}

Driver opens an connection to the underlying database.

type DriverFunc

type DriverFunc func(appName string, accessModel AccessModel, optionString string, migrate bool) (Conn, error)

The DriverFunc type is an adapter such that an ordinary function can be used as a Driver.

func (DriverFunc) Open

func (f DriverFunc) Open(appName string, accessModel AccessModel, name string, migrate bool) (Conn, error)

Open returns a Conn by calling the DriverFunc itself.

type Expression

type Expression struct {
	Type  ExpressionType
	Value interface{}
}

An Expression represents value to be compared against.

func (Expression) IsEmpty added in v0.3.0

func (expr Expression) IsEmpty() bool

func (Expression) IsKeyPath

func (expr Expression) IsKeyPath() bool

func (Expression) IsLiteralArray

func (expr Expression) IsLiteralArray() bool

func (Expression) IsLiteralMap

func (expr Expression) IsLiteralMap() bool

func (Expression) IsLiteralNull added in v0.10.0

func (expr Expression) IsLiteralNull() bool

func (Expression) IsLiteralString

func (expr Expression) IsLiteralString() bool

func (Expression) KeyPathComponents added in v0.14.0

func (expr Expression) KeyPathComponents() []string

type ExpressionType

type ExpressionType int

ExpressionType is the type of an Expression.

const (
	Literal ExpressionType = iota + 1
	KeyPath
	Function
)

A list of ExpressionTypes.

type FieldType

type FieldType struct {
	Type          DataType
	ReferenceType string     // used only by TypeReference
	Expression    Expression // used by Computed Keys
}

FieldType represents the kind of data living within a field of a RecordSchema.

func SimpleNameToFieldType added in v0.5.0

func SimpleNameToFieldType(s string) (result FieldType, err error)

func (FieldType) DefinitionEquals added in v0.15.0

func (f FieldType) DefinitionEquals(other FieldType) bool

func (FieldType) ToSimpleName added in v0.5.0

func (f FieldType) ToSimpleName() string

type Func

type Func interface {
	Args() []interface{}
}

Func is a marker interface to denote a type being a function in skydb.

skydb's function receives zero or more arguments and returns a DataType as a result. Result data type is currently omitted in this interface since skygear doesn't use it internally yet. In the future it can be utilized to provide more extensive type checking at handler level.

type Location

type Location [2]float64

Location represent a point of geometry.

It being an array of two floats is intended to provide no-copy conversion between paulmach/go.geo.Point.

func NewLocation

func NewLocation(lng, lat float64) Location

NewLocation returns a new Location

func (Location) Lat

func (loc Location) Lat() float64

Lat returns the Latitude

func (Location) Lng

func (loc Location) Lng() float64

Lng returns the longitude

func (Location) String

func (loc Location) String() string

String returns a human-readable representation of this Location. Coincidentally it is in WKT.

type MemoryRows

type MemoryRows struct {
	CurrentRowIndex int
	Records         []Record
}

MemoryRows is a native implementation of RowIter. Can be used in test not support cursor.

func NewMemoryRows

func NewMemoryRows(records []Record) *MemoryRows

func (*MemoryRows) Close

func (rs *MemoryRows) Close() error

func (*MemoryRows) Next

func (rs *MemoryRows) Next(record *Record) error

func (*MemoryRows) OverallRecordCount

func (rs *MemoryRows) OverallRecordCount() *uint64

type NotificationInfo

type NotificationInfo struct {
	APS APSSetting `json:"aps,omitempty"`
}

NotificationInfo describes how server should send a notification to a target devices via a push service. Currently only APS is supported.

type Operator

type Operator int

Operator denotes how the result of a predicate is determined from its subpredicates or subexpressions.

const (
	And Operator = iota + 1
	Or
	Not
	Equal
	GreaterThan
	LessThan
	GreaterThanOrEqual
	LessThanOrEqual
	NotEqual
	Like
	ILike
	In
	Functional
)

A list of Operator.

func (Operator) IsBinary

func (op Operator) IsBinary() bool

IsBinary checks whether the Operator determines the result of a predicate by comparing two subexpressions.

func (Operator) IsCommutative added in v0.10.0

func (op Operator) IsCommutative() bool

IsCommutative checks whether expressions on both side of the Operator can be swapped.

func (Operator) IsCompound

func (op Operator) IsCompound() bool

IsCompound checks whether the Operator is a compound operator, meaning the operator combine the results of other subpredicates.

func (Operator) String added in v0.6.0

func (i Operator) String() string

type Predicate

type Predicate struct {
	Operator Operator
	Children []interface{}
}

Predicate is a representation of used in query for filtering records.

func (Predicate) GetExpressions

func (p Predicate) GetExpressions() (ps []Expression)

GetExpressions returns Predicate.Children as []Expression.

This method is only valid when Operator is binary operator. Caller is responsible to check for this preconditions. Otherwise the method will panic.

func (Predicate) GetSubPredicates

func (p Predicate) GetSubPredicates() (ps []Predicate)

GetSubPredicates returns Predicate.Children as []Predicate.

This method is only valid when Operator is either And, Or and Not. Caller is responsible to check for this preconditions. Otherwise the method will panic.

func (Predicate) IsEmpty added in v0.3.0

func (p Predicate) IsEmpty() bool

func (Predicate) Validate

func (p Predicate) Validate() skyerr.Error

Validate returns an Error if a Predicate is invalid.

If a Predicate is validated without error, nil is returned.

type Query

type Query struct {
	Type         string
	Predicate    Predicate
	Sorts        []Sort
	ComputedKeys map[string]Expression
	DesiredKeys  []string
	GetCount     bool
	Limit        *uint64
	Offset       uint64

	// The following fields are generated from the server side, rather
	// than supplied from the client side.
	ViewAsUser          *UserInfo
	BypassAccessControl bool
}

Query specifies the type, predicate and sorting order of Database query.

type QueryConfig added in v0.3.0

type QueryConfig struct {
	Limit  uint64
	Offset uint64
}

QueryConfig provides optional parameters for queries. result is unlimited if Limit=0

type Record

type Record struct {
	ID         RecordID
	DatabaseID string `json:"-"`
	OwnerID    string
	CreatedAt  time.Time
	CreatorID  string
	UpdatedAt  time.Time
	UpdaterID  string
	ACL        RecordACL
	Data       Data
	Transient  Data `json:"-"`
}

Record is the primary entity of storage in Skygear.

func (*Record) Accessible added in v0.7.0

func (r *Record) Accessible(userinfo *UserInfo, level ACLLevel) bool

func (*Record) Get

func (r *Record) Get(key string) interface{}

Get returns the value specified by key. If no value is associated with the specified key, it returns nil.

Get also supports getting reserved fields starting with "_". If such reserved field does not exists, it returns nil.

func (*Record) Set

func (r *Record) Set(key string, i interface{})

Set associates key with the value i in this record.

Set is able to associate reserved key name starting with "_" as well. If there is no such key, it panics.

type RecordACL

type RecordACL []RecordACLEntry

RecordACL is a list of ACL entries defining access control for a record

func NewRecordACL

func NewRecordACL(entries []RecordACLEntry) RecordACL

NewRecordACL returns a new RecordACL

func (RecordACL) Accessible added in v0.9.0

func (acl RecordACL) Accessible(userinfo *UserInfo, level ACLLevel) bool

Accessible checks whether provided user info has certain access level

type RecordACLEntry

type RecordACLEntry struct {
	Relation string   `json:"relation,omitempty"`
	Role     string   `json:"role,omitempty"`
	Level    ACLLevel `json:"level"`
	UserID   string   `json:"user_id,omitempty"`
	Public   bool     `json:"public,omitempty"`
}

RecordACLEntry grants access to a record by relation or by user_id

func NewRecordACLEntryDirect

func NewRecordACLEntryDirect(userID string, level ACLLevel) RecordACLEntry

NewRecordACLEntryDirect returns an ACE for a specific user

func NewRecordACLEntryPublic added in v0.10.0

func NewRecordACLEntryPublic(level ACLLevel) RecordACLEntry

NewRecordACLEntryPublic return an ACE on public access

func NewRecordACLEntryRelation

func NewRecordACLEntryRelation(relation string, level ACLLevel) RecordACLEntry

NewRecordACLEntryRelation returns an ACE on relation

func NewRecordACLEntryRole added in v0.7.0

func NewRecordACLEntryRole(role string, level ACLLevel) RecordACLEntry

NewRecordACLEntryRole return an ACE on role

func (*RecordACLEntry) Accessible added in v0.7.0

func (ace *RecordACLEntry) Accessible(userinfo *UserInfo, level ACLLevel) bool

func (*RecordACLEntry) AccessibleLevel added in v0.7.0

func (ace *RecordACLEntry) AccessibleLevel(level ACLLevel) bool

type RecordEvent

type RecordEvent struct {
	Record *Record
	Event  RecordHookEvent
}

RecordEvent describes a change event on Record which is either Created, Updated or Deleted.

For RecordCreated or RecordUpdated event, Record is the newly created / updated Record. For RecordDeleted, Record is the Record being deleted.

type RecordHookEvent

type RecordHookEvent int

RecordHookEvent indicates the type of record event that triggered the hook

const (
	RecordCreated RecordHookEvent = iota + 1
	RecordUpdated
	RecordDeleted
)

See the definition of RecordHookEvent

type RecordID

type RecordID struct {
	Type string
	Key  string
}

RecordID identifies an unique record in a Database

func NewEmptyRecordID added in v0.5.0

func NewEmptyRecordID() RecordID

func NewRecordID

func NewRecordID(recordType string, id string) RecordID

NewRecordID returns a new RecordID

func (*RecordID) IsEmpty added in v0.5.0

func (id *RecordID) IsEmpty() bool

IsEmpty returns whether the RecordID is empty.

func (RecordID) MarshalText

func (id RecordID) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextUnmarshaler interface.

func (RecordID) String

func (id RecordID) String() string

String implements the fmt.Stringer interface.

func (*RecordID) UnmarshalText

func (id *RecordID) UnmarshalText(data []byte) error

UnmarshalText implements the encoding.TextMarshaler interface.

type RecordSchema

type RecordSchema map[string]FieldType

RecordSchema is a mapping of record key to its value's data type or reference

func (RecordSchema) DefinitionEquals added in v0.15.0

func (schema RecordSchema) DefinitionEquals(other RecordSchema) bool

type Reference

type Reference struct {
	ID RecordID
}

func NewEmptyReference added in v0.5.0

func NewEmptyReference() Reference

NewEmptyReference returns a reference that is empty

func NewReference

func NewReference(recordType string, id string) Reference

func (*Reference) IsEmpty added in v0.5.0

func (reference *Reference) IsEmpty() bool

IsEmpty returns whether the reference is empty.

func (*Reference) Type

func (reference *Reference) Type() string

type Rows

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

Rows implements a scanner-like interface for easy iteration on a result set returned from a query

func NewRows

func NewRows(iter RowsIter) *Rows

NewRows creates a new Rows.

Driver implementators are expected to call this method with their implementation of RowsIter to return a Rows from Database.Query.

func (*Rows) Close

func (r *Rows) Close() error

Close closes the Rows and prevents futher enumerations on the instance.

func (*Rows) Err

func (r *Rows) Err() error

Err returns the last error encountered during Scan.

NOTE: It is not an error if the underlying result set is exhausted.

func (*Rows) OverallRecordCount

func (r *Rows) OverallRecordCount() *uint64

OverallRecordCount returns the number of matching records in the database if this resultset contains any rows.

func (*Rows) Record

func (r *Rows) Record() Record

Record returns the current record in Rows.

It must be called after calling Scan and Scan returned true. If Scan is not called or previous Scan return false, the behaviour of Record is unspecified.

func (*Rows) Scan

func (r *Rows) Scan() bool

Scan tries to prepare the next record and returns whether such record is ready to be read.

type RowsIter

type RowsIter interface {
	// Close closes the rows iterator
	Close() error

	// Next populates the next Record in the current rows iterator into
	// the provided record.
	//
	// Next should return io.EOF when there are no more rows
	Next(record *Record) error

	OverallRecordCount() *uint64
}

RowsIter is an iterator on results returned by execution of a query.

type Sequence

type Sequence struct{}

Sequence is a bogus data type for creating a sequence field via JIT schema migration

type Sort

type Sort struct {
	KeyPath string
	Func    Func
	Order   SortOrder
}

Sort specifies the order of a collection of Records returned from a Query.

Record order can be sorted w.r.t. a record field or a value returned from a predefined function.

type SortOrder

type SortOrder int

SortOrder denotes an the order of Records returned from a Query.

type Subscription

type Subscription struct {
	ID               string            `json:"id"`
	Type             string            `json:"type"`
	DeviceID         string            `json:"device_id"`
	NotificationInfo *NotificationInfo `json:"notification_info,omitempty"`
	Query            Query             `json:"query"`
}

Subscription represents a device's subscription of notification triggered by changes of results from a query.

type TxDatabase

type TxDatabase interface {
	// Begin opens a transaction for the current Database.
	//
	// Calling Begin on an already Begin'ed Database returns ErrDatabaseTxDidBegin.
	Begin() error

	// Commit saves all the changes made to Database after Begin atomically.
	Commit() error

	// Rollbacks discards all the changes made to Database after Begin.
	Rollback() error
}

TxDatabase defines the methods for a Database that supports transaction.

A Begin'ed transaction must end with a call to Commit or Rollback. After that, all opertions on Database will return ErrDatabaseTxDone.

NOTE(limouren): The interface is not Database specific, but currently only Database supports it.

type UserDataFunc added in v0.5.0

type UserDataFunc struct {
	DataName string
}

UserDataFunc is an expresssion to return an attribute of user info as email addresses. Can only be used with user record.

func (UserDataFunc) Args added in v0.5.0

func (f UserDataFunc) Args() []interface{}

Args implements the Func interface

type UserDiscoverFunc added in v0.5.0

type UserDiscoverFunc struct {
	Usernames []string
	Emails    []string
}

UserDiscoverFunc searches for user record having the specified user data, such as email addresses. Can only be used with user record.

func (UserDiscoverFunc) Args added in v0.5.0

func (f UserDiscoverFunc) Args() []interface{}

Args implements the Func interface

func (UserDiscoverFunc) ArgsByName added in v0.5.0

func (f UserDiscoverFunc) ArgsByName(name string) []interface{}

ArgsByName implements the Func interface

func (UserDiscoverFunc) HaveArgsByName added in v0.15.0

func (f UserDiscoverFunc) HaveArgsByName(name string) bool

HaveArgsByName implements the Func interface

type UserInfo

type UserInfo struct {
	ID              string     `json:"_id"`
	Username        string     `json:"username,omitempty"`
	Email           string     `json:"email,omitempty"`
	HashedPassword  []byte     `json:"password,omitempty"`
	Roles           []string   `json:"roles,omitempty"`
	Auth            AuthInfo   `json:"auth,omitempty"` // auth data for alternative methods
	TokenValidSince *time.Time `json:"token_valid_since,omitempty"`
}

UserInfo contains a user's information for authentication purpose

func NewAnonymousUserInfo

func NewAnonymousUserInfo() UserInfo

NewAnonymousUserInfo returns an anonymous UserInfo, which has no Email and Password.

func NewProvidedAuthUserInfo

func NewProvidedAuthUserInfo(principalID string, authData map[string]interface{}) UserInfo

NewProvidedAuthUserInfo returns an UserInfo provided by a AuthProvider, which has no Email and Password.

func NewUserInfo

func NewUserInfo(username string, email string, password string) UserInfo

NewUserInfo returns a new UserInfo with specified username, email and password. An UUID4 ID will be generated by the system as unique identifier

func (*UserInfo) GetProvidedAuthData

func (info *UserInfo) GetProvidedAuthData(principalID string) map[string]interface{}

GetProvidedAuthData gets the auth data for the specified principal.

func (*UserInfo) HasAllRoles added in v0.6.0

func (info *UserInfo) HasAllRoles(roles []string) bool

HasAllRoles return true if userinfo has all roles supplied

func (*UserInfo) HasAnyRoles added in v0.6.0

func (info *UserInfo) HasAnyRoles(roles []string) bool

HasAnyRoles return true if userinfo belongs to one of the supplied roles

func (UserInfo) IsSamePassword

func (info UserInfo) IsSamePassword(password string) bool

IsSamePassword determines whether the specified password is the same password as where the HashedPassword is generated from

func (*UserInfo) RemoveProvidedAuthData

func (info *UserInfo) RemoveProvidedAuthData(principalID string)

RemoveProvidedAuthData remove the auth data for the specified principal.

func (*UserInfo) SetPassword

func (info *UserInfo) SetPassword(password string)

SetPassword sets the HashedPassword with the password specified

func (*UserInfo) SetProvidedAuthData

func (info *UserInfo) SetProvidedAuthData(principalID string, authData map[string]interface{})

SetProvidedAuthData sets the auth data to the specified principal.

type UserRelationFunc

type UserRelationFunc struct {
	KeyPath           string
	RelationName      string
	RelationDirection string
	User              string
}

UserRelationFunc represents a function that is used to evaulate whether a record satisfy certain user-based relation

func (UserRelationFunc) Args

func (f UserRelationFunc) Args() []interface{}

Args implements the Func interface

Directories

Path Synopsis
pq

Jump to

Keyboard shortcuts

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