goloquent

package module
Version: v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2021 License: MIT Imports: 23 Imported by: 3

README

Goloquent

The only sequel ORM that respect google datastore.

Why Goloquent?

Few years back, we required to migrate our database to local due to compliance issue, and there have no way to map back the data to SQL database. For sake, we introduce goloquent for whoever want to migrate their google datastore to SQL database.

Database Support

  • MySQL (version 5.7 and above)
  • Postgres (version 9.4 and above)

This package is not compactible with native package database/sql, if you want the support of it, you may go for sqlike

Sequel Datastore ORM

Inspired by Laravel Eloquent and Google Cloud Datastore

This repo still under development. We accept any pull request. ^_^

Installation

  // dependency
  $ go get -u github.com/go-sql-driver/mysql // Mysql
  $ go get -u github.com/lib/pq // Postgres
  $ go get -u cloud.google.com/go/datastore
  $ go get -u github.com/si3nloong/goloquent
  • Import the library
  import "github.com/si3nloong/goloquent"

Quick Start

Connect to database
    import "github.com/si3nloong/goloquent/db"

    conn, err := db.Open("mysql", db.Config{
        Username: "root",
        Password: "",
        Host: "localhost",
        Port: "3306",
        Database: "test",
        Logger: func(stmt *goloquent.Stmt) {
            log.Println(stmt.TimeElapse()) // elapse time in time.Duration
            log.Println(stmt.String()) // Sql string without any ?
            log.Println(stmt.Raw()) // Sql prepare statement
            log.Println(stmt.Arguments()) // Sql prepare statement's arguments
            log.Println(fmt.Sprintf("[%.3fms] %s", stmt.TimeElapse().Seconds()*1000, stmt.String()))
        },
    })
    defer conn.Close()
    if err != nil {
        panic("Connection error: ", err)
    }
User Table
// Address :
type Address struct {
	Line1    string
	Line2    string
	Country  string
	PostCode uint
	Region   struct {
		TimeZone    time.Time
		Keys        []*datastore.Key   `goloquent:"keys"`
		CountryCode string             `goloquent:"regionCode"`
		Geolocation datastore.GeoPoint `goloquent:"geo"`
	} `goloquent:"region"`
}

// User : User kind parent is Merchant
type User struct {
    Key             *datastore.Key `goloquent:"__key__"` // load table key
    Name            string
    Nicknames       []string
    CountryCode     string
    PhoneNumber     string
    Email           string
    BirthDate       goloquent.Date
    Address         Address
    Age             uint8
    ExtraInfo       json.RawMessage
    CreatedDateTime time.Time
    UpdatedDateTime time.Time
}

// Load : load func will execute after load
func (x *User) Load() error {
	return nil
}

// Save : save func will execute before save
func (x *User) Save() (error) {
	return nil
}
Helper
    // StringPrimaryKey is to get key value in string form
    key := datastore.NameKey("Merchant", "mjfFgYnxBS", nil)
    fmt.Println(goloquent.StringKey(key)) // "mjfFgYnxBS"

    key = datastore.IDKey("User", int64(2305297334603281546), nil)
    fmt.Println(goloquent.StringKey(key)) // "2305297334603281546"

    key = datastore.NameKey("User", int64(2305297334603281546), datastore.NameKey("Merchant", "mjfFgYnxBS", nil))
    fmt.Println(goloquent.StringifyKey(key)) // Merchant,'mjfFgYnxBS'/User,2305297334603281546
Table
    import "github.com/si3nloong/goloquent/db"

    // Check table exists
    db.Table("User").Exists() // true

    // Drop table if exists
    if err := db.Table("User").DropIfExists(); err != nil {
        log.Fatal(err)
    }

    // Add index
    if err := db.Table("User").AddIndex("Name", "Email"); err != nil {
        log.Fatal(err)
    }

    // Add unique index
    if err := db.Table("User").AddUniqueIndex("Email"); err != nil {
        log.Fatal(err)
    }
Create Record
    import "github.com/si3nloong/goloquent/db"

    // Example
    user := new(User)
    user.Name = "Hello World"
    user.Age = 18

    // OR
    var user *User
    user.Name = "Hello World"
    user.Age = 18

    // Create without parent key
    if err := db.Create(user, nil); err != nil {
        log.Println(err) // fail to create record
    }

    // Create with parent key
    parentKey := datastore.NameKey("Parent", "value", nil)
    if err := db.Create(user, parentKey); err != nil {
        log.Println(err) // fail to create record
    }

    // Create without key, goloquent will auto generate primary key
    if err := db.Create(user); err != nil {
        log.Println(err) // fail to create record
    }

    // Create with self generate key
    user.Key = datastore.NameKey("User", "uniqueID", nil)
    if err := db.Create(user); err != nil {
        log.Println(err) // fail to create record
    }
Upsert Record
    import "github.com/si3nloong/goloquent/db"

    // Example
    user := new(User)
    user.Name = "Hello World"
    user.Age = 18

    // Update if key exists, else create the user record
    parentKey := datastore.NameKey("Parent", "value", nil)
    if err := db.Upsert(user, parentKey); err != nil {
        log.Println(err) // fail
    }

    // Upsert with self generate key
    user := new(User)
    user.Key = datastore.NameKey("User", "uniqueID", nil)
    user.Name = "Hello World"
    user.Age = 18
    if err := db.Upsert(user); err != nil {
        log.Println(err) // fail
    }
Retrieve Record
  • Get Single Record using Primary Key
    // Example
    primaryKey := datastore.IDKey("User", int64(2305297334603281546), nil)
    user := new(User)
    if err := db.Find(primaryKey, user); err != nil {
        log.Println(err) // error while retrieving record
    }

    if err := db.Where("Status", "=", "ACTIVE").
        Find(primaryKey, user); err != goloquent.ErrNoSuchEntity {
        // if no record found using primary key, error `ErrNoSuchEntity` will throw instead
        log.Println(err) // error while retrieving record
    }
  • Get Single Record
    import "github.com/si3nloong/goloquent/db"
    // Example 1
    user := new(User)
    if err := db.First(user); err != nil {
        log.Println(err) // error while retrieving record
    }

    if user.Key != nil { // if have record
        fmt.Println("Have record")
    } else { // no record
        fmt.Println("Doesnt't have record")
    }

    // Example 2
    user := new(User)
    if err := db.Where("Email", "=", "admin@hotmail.com").
        First(user); err != nil {
        log.Println(err) // error while retrieving record
    }

    // Example 3
    age := 22
    parentKey := datastore.IDKey("Parent", 1093, nil)
    user := new(User)
    if err := db.Ancestor(parentKey).
        WhereEqual("Age", &age).
        OrderBy("-CreatedDateTime").
        First(user); err != nil {
        log.Println(err) // error while retrieving record
    }
  • Get Multiple Record
    import "github.com/si3nloong/goloquent/db"
    // Example 1
    users := new([]User)
    if err := db.Limit(10).Get(users); err != nil {
        log.Println(err) // error while retrieving record
    }

    // Example 2
    users := new([]*User)
    if err := db.WhereEqual("Name", "Hello World").
        Get(users); err != nil {
        log.Println(err) // error while retrieving record
    }

    // Example 3
    users := new([]User)
    if err := db.Ancestor(parentKey).
        WhereEqual("Name", "myz").
        WhereEqual("Age", 22).
        Get(users); err != nil {
        log.Println(err) // error while retrieving record
    }
  • Get Record with OrderBying
    import "github.com/si3nloong/goloquent/db"
    // Ascending OrderBy
    users := new([]*User)
    if err := db.OrderBy("CreatedDateTime").
        Get(users); err != nil {
        log.Println(err) // error while retrieving record
    }

    // Descending OrderBy
    if err := db.Table("User").
        OrderBy("-CreatedDateTime").
        Get(users); err != nil {
        log.Println(err) // error while retrieving record
    }
  • Pagination Record
    import "github.com/si3nloong/goloquent/db"

    p := goloquent.Pagination{
        Limit:  10,
        Cursor: "", // pass the cursor that generate by the query so that it will display the next record
    }

    // Example
    users := new([]*User)
    if err := db.Ancestor(parentKey).
        OrderBy("-CreatedDateTime").
        Paginate(&p, users); err != nil {
        log.Println(err) // error while retrieving record
    }

    // ***************** OR ********************
    p := &goloquent.Pagination{
        Limit:  10, // number of records in each page
        Cursor: "EhQKCE1lcmNoYW50EK3bueKni5eNIxIWCgxMb3lhbHR5UG9pbnQaBkZrUUc4eA", // pass the cursor to get next record set
    }

    users := new([]*User)
    if err := db.Ancestor(parentKey).
        OrderBy("-CreatedDateTime").
        Paginate(p, users); err != nil {
        log.Println(err) // error while retrieving record
    }

    log.Println(p.NextCursor()) // next page cursor
    log.Println(p.Count()) // record count
Save Record
    import "github.com/si3nloong/goloquent/db"
    // Example
    if err := db.Save(user); err != nil {
        log.Println(err) // fail to delete record
    }
Delete Record
  • Delete using Primary Key
    import "github.com/si3nloong/goloquent/db"
    // Example
    if err := db.Delete(user); err != nil {
        log.Println(err) // fail to delete record
    }
  • Delete using Where statement
    // Delete user table record which account type not equal to "PREMIUM" or "MONTLY"
    if err := db.Table("User").
        WhereNotIn("AccountType", []string{
            "PREMIUM", "MONTLY",
        }).Flush(); err != nil {
        log.Println(err) // fail to delete record
    }
Transaction
    // Example
    if err := db.RunInTransaction(func(txn *goloquent.DB) error {
        user := new(User)
        if err := txn.Create(user, nil); err != nil {
            return err // return any err to rollback the transaction
        }
        return nil // return nil to commit the transaction
    }); err != nil {
        log.Println(err)
    }
  • Table Locking (only effective inside RunInTransaction)
    // Example
    merchantKey := datastore.IDKey("Merchant", "mjfFgYnxBS", nil)
    userKey := datastore.IDKey("User", int64(4645436182170916864), nil)
    if err := db.RunInTransaction(func(txn *goloquent.DB) error {
        user := new(User)

        if err := txn.NewQuery().
            WLock(). // Lock record for update
            Find(userKey, user); err != nil {
            return err
        }

        merchant := new(Merchant)
        if err := txn.NewQuery().
            RLock(). // Lock record for read
            Find(merchantKey, merchant); err != nil {
            return err
        }

        user.Age = 30
        if err := txn.Save(user); err != nil {
            return err // return any err to rollback the transaction
        }

        return nil // return nil to commit the transaction
    }); err != nil {
        log.Println(err)
    }
  • Database Migration
    import "github.com/si3nloong/goloquent/db"
    // Example
    user := new(User)
    if err := db.Migrate(
        new(user),
        Merchant{},
        &Log{},
    ); err != nil {
        log.Println(err)
    }
  • Filter Query
    import "github.com/si3nloong/goloquent/db"
    // Update single record
    user := new(User)
    if err := db.NewQuery().
        WhereIn("Status", []interface{}{"active", "pending"}).
        First(user); err != nil {
        log.Println(err) // error while retrieving record or record not found
    }

    // Get record with like
    if err := db.NewQuery().
        WhereLike("Name", "%name%").
        First(user); err != nil {
        log.Println(err) // error while retrieving record or record not found
    }
  • Update Query
    import "github.com/si3nloong/goloquent/db"
    // Update multiple record
    if err := db.Table("User").
        Where("Age", ">", 10).
        Update(map[string]interface{}{
            "Name": "New Name",
            "Email": "email@gmail.com",
            "UpdatedDateTime": time.Now().UTC(),
        }); err != nil {
        log.Println(err) // error while retrieving record or record not found
    }

    if err := db.Table("User").
        Omit("Name").
        Where("Age", ">", 10).
        Update(User{
            Name: "New Name",
            Email: "test@gmail.com",
            UpdatedDateTime: time.Now().UTC(),
        }); err != nil {
        log.Println(err) // error while retrieving record or record not found
    }
  • JSON Filter
    import "github.com/si3nloong/goloquent/db"

    // JSON equal
    users := new([]User)
    postCode := uint32(63000)
	if err := db.NewQuery().
		WhereJSONEqual("Address>PostCode", &postCode).
		Get(users); err != nil {
		log.Println(err)
    }

    // JSON not equal
    var timeZone *time.Time
	if err := db.NewQuery().
		WhereJSONNotEqual("Address>region.TimeZone", timeZone).
		Get(users); err != nil {
		log.Println(err)
    }

    // JSON contains any
    if err := db.NewQuery().
		WhereJSONContainAny("Nicknames", []string{
            "Joe", "John", "Robert",
        }).Get(users); err != nil {
		log.Println(err)
    }

    // JSON check type
    if err := db.NewQuery().
		WhereJSONType("Address>region", "Object").
        Get(users); err != nil {
		log.Println(err)
    }

    // JSON check is object type
    if err := db.NewQuery().
		WhereJSONIsObject("Address>region").
        Get(users); err != nil {
		log.Println(err)
    }

    // JSON check is array type
    if err := db.NewQuery().
		WhereJSONIsArray("Address>region.keys").
        Get(users); err != nil {
		log.Println(err)
    }
  • Data Type Support for Where Filtering

The supported data type are :

- string
- bool
- int, int8, int16, int32 and int64 (signed integers)
- uint, uint8, uint16, uint32 and uint64
- float32 and float64
- []byte
- datastore.GeoPoint
- goloquent.Date
- json.RawMessage
- time.Time
- pointers to any one of the above
- *datastore.Key
- slices of any of the above
  • Extra Schema Option

Available shorthand:

  • longtext (only applicable for string data type)
  • index
  • unsigned (only applicable for float32 and float64 data type)
  • flatten (only applicable for struct or []struct)
type model struct {
    CreatedDateTime time.Time // `CreatedDateTime`
    UpdatedDateTime time.Time // `UpdatedDateTime`
}

// Fields may have a `goloquent:"name,options"` tag.
type User struct {
    Key         *datastore.Key `goloquent:"__key__"` // Primary Key
    Name        string `goloquent:",longtext"` // Using `TEXT` datatype instead of `VARCHAR(255)` by default
    CreditLimit    float64    `goloquent:",unsigned"` // Unsigned option only applicable for float32 & float64 data type
    PhoneNumber string `goloquent:",charset=utf8,collate=utf8_bin,datatype=char(20)"`
    Email       string
    Skip        string `goloquent:"-"` // Skip this field to store in db
    DefaultAddress struct {
        AddressLine1 string // `DefaultAddress.AddressLine1`
        AddressLine2 string // `DefaultAddress.AddressLine2`
        PostCode     int    // `DefaultAddress.PostCode`
        City         string // `DefaultAddress.City`
        State        string // `DefaultAddress.State`
        Country      string
    } `goloquent:",flatten"` // Flatten the struct field
    Birthdate *goloquent.Date
    ExtraInfo json.RawMessage
    model                    // Embedded struct
    Deleted goloquent.SoftDelete
}

The supported data type are :

- string
- int, int8, int16, int32 and int64 (signed integers)
- uint, uint8, uint16, uint32 and uint64
- bool
- float32 and float64
- []byte
- any type whose underlying type is one of the above predeclared types
- datastore.GeoPoint
- goloquent.Date
- goloquent.SoftDelete
- time.Time
- json.RawMessage
- structs whose fields are all valid value types
- pointers to any one of the above
- *datastore.Key
- slices of any of the above
Data Type Mysql Postgres Default Value CharSet
*datastore.Key varchar(512) varchar(512) latin1
datastore.GeoPoint varchar(50) varchar(50) {Lat: 0, Lng: 0}
string varchar(191) varchar(191) "" utf8mb4
[]byte mediumblob bytea
bool boolean bool false
float32 double real 0
float64 double real 0
int int integer 0
int8 tinyint smallint 0
int16 smallint smallint 0
int32 mediumint integer 0
int64 bigint bigint 0
uint int (unsigned) integer (unsigned) 0
uint8 smallint (unsigned) smallint (unsigned) 0
uint16 smallint (unsigned) smallint (unsigned) 0
uint32 smallint (unsigned) integer (unsigned) 0
uint64 bigint (unsigned) bigint (unsigned) 0
slice or array json jsonb
struct json jsonb
json.RawMessage json jsonb
Date date date 0001-01-01
time.Time datetime timestamp 0001-01-01 00:00:00
SoftDelete datetime (nullable) timestamp NULL

$Key, $Deleted are reserved words, please avoid to use these words as your column name

MIT License

Documentation

Index

Constants

View Source
const (
	Equal operator = iota
	EqualTo
	NotEqual
	LessThan
	LessEqual
	GreaterThan
	GreaterEqual
	AnyLike
	Like
	NotLike
	ContainAny
	ContainAll
	In
	NotIn
	IsObject
	IsArray
	IsType
	MatchAgainst
)

JSON :

View Source
const (
	ReadLock locked = iota + 1
	WriteLock
)

lock mode

Variables

View Source
var (
	ErrNoSuchEntity  = fmt.Errorf("goloquent: entity not found")
	ErrInvalidCursor = fmt.Errorf("goloquent: invalid cursor")
)

CommonError :

Functions

func LoadStruct

func LoadStruct(src interface{}, data map[string]interface{}) error

LoadStruct :

func ParseKey

func ParseKey(str string) (*datastore.Key, error)

ParseKey :

func RegisterDialect

func RegisterDialect(driver string, d Dialect)

RegisterDialect :

func SaveStruct

func SaveStruct(src interface{}) (map[string]Property, error)

SaveStruct :

func SetPKSimple added in v0.1.0

func SetPKSimple(flag bool)

SetPKSimple :

func StringKey

func StringKey(key *datastore.Key) string

StringKey :

func StringifyKey

func StringifyKey(key *datastore.Key) string

StringifyKey :

Types

type CharSet

type CharSet struct {
	Encoding  string
	Collation string
}

CharSet :

type Client

type Client struct {
	CharSet
	// contains filtered or unexported fields
}

Client :

func (Client) Exec

func (c Client) Exec(query string, args ...interface{}) (sql.Result, error)

Exec :

func (Client) PrepareExec

func (c Client) PrepareExec(query string, args ...interface{}) (sql.Result, error)

PrepareExec :

func (Client) Query

func (c Client) Query(query string, args ...interface{}) (*sql.Rows, error)

Query :

func (Client) QueryRow

func (c Client) QueryRow(query string, args ...interface{}) *sql.Row

QueryRow :

type Column

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

Column :

func (Column) Name

func (c Column) Name() string

Name :

type Config

type Config struct {
	Username   string
	Password   string
	Host       string
	Port       string
	Database   string
	UnixSocket string
	TLSConfig  string
	CharSet    *CharSet
	Logger     LogHandler
}

Config :

func (*Config) Normalize

func (c *Config) Normalize()

Normalize :

type Cursor

type Cursor struct {
	Signature string         `json:"signature"`
	Key       *datastore.Key `json:"next"`
	// contains filtered or unexported fields
}

Cursor :

func DecodeCursor

func DecodeCursor(c string) (Cursor, error)

DecodeCursor :

func (Cursor) String

func (c Cursor) String() string

String :

type DB

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

DB :

func NewDB

func NewDB(driver string, charset CharSet, conn sqlCommon, dialect Dialect, logHandler LogHandler) *DB

NewDB :

func (*DB) Ancestor

func (db *DB) Ancestor(ancestor *datastore.Key) *Query

Ancestor :

func (*DB) AnyOfAncestor

func (db *DB) AnyOfAncestor(ancestors ...*datastore.Key) *Query

AnyOfAncestor :

func (*DB) Close

func (db *DB) Close() error

Close :

func (*DB) Create

func (db *DB) Create(model interface{}, parentKey ...*datastore.Key) error

Create :

func (*DB) Delete

func (db *DB) Delete(model interface{}) error

Delete :

func (*DB) Destroy

func (db *DB) Destroy(model interface{}) error

Destroy :

func (*DB) Exec

func (db *DB) Exec(stmt string, args ...interface{}) (sql.Result, error)

Exec :

func (*DB) Find

func (db *DB) Find(key *datastore.Key, model interface{}) error

Find :

func (*DB) First

func (db *DB) First(model interface{}) error

First :

func (*DB) Get

func (db *DB) Get(model interface{}) error

Get :

func (DB) ID

func (db DB) ID() string

ID :

func (*DB) MatchAgainst added in v0.5.0

func (db *DB) MatchAgainst(fields []string, value ...string) *Query

Where :

func (*DB) Migrate

func (db *DB) Migrate(model ...interface{}) error

Migrate :

func (DB) Name

func (db DB) Name() string

Name :

func (*DB) NewQuery

func (db *DB) NewQuery() *Query

NewQuery :

func (*DB) Omit

func (db *DB) Omit(fields ...string) Replacer

Omit :

func (*DB) Paginate

func (db *DB) Paginate(p *Pagination, model interface{}) error

Paginate :

func (*DB) Query

func (db *DB) Query(stmt string, args ...interface{}) (*sql.Rows, error)

Query :

func (*DB) RunInTransaction

func (db *DB) RunInTransaction(cb TransactionHandler) error

RunInTransaction :

func (*DB) Save

func (db *DB) Save(model interface{}) error

Save :

func (*DB) Select

func (db *DB) Select(fields ...string) *Query

Select :

func (*DB) Table

func (db *DB) Table(name string) *Table

Table :

func (*DB) Truncate

func (db *DB) Truncate(model ...interface{}) error

Truncate :

func (*DB) Upsert

func (db *DB) Upsert(model interface{}, parentKey ...*datastore.Key) error

Upsert :

func (*DB) Where

func (db *DB) Where(field string, operator string, value interface{}) *Query

Where :

type Date

type Date time.Time

Date :

func (Date) MarshalJSON

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

MarshalJSON :

func (Date) MarshalText

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

MarshalText :

func (Date) String

func (d Date) String() string

String :

func (*Date) UnmarshalJSON

func (d *Date) UnmarshalJSON(b []byte) error

UnmarshalJSON :

func (*Date) UnmarshalText

func (d *Date) UnmarshalText(b []byte) error

UnmarshalText :

type DefaultEncoder added in v0.3.0

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

type DefaultStmtEncoder added in v0.3.0

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

type Dialect

type Dialect interface {
	Open(c Config) (*sql.DB, error)
	SetDB(db Client)
	GetTable(ns string) string
	Version() (ver string)
	CurrentDB() (n string)
	Quote(n string) string
	Bind(i uint) string
	FilterJSON(f Filter) (s string, args []interface{}, err error)
	JSONMarshal(i interface{}) (b json.RawMessage)
	Value(v interface{}) string
	GetSchema(c Column) []Schema
	DataType(s Schema) string
	HasTable(tb string) bool
	HasIndex(tb, idx string) bool
	GetColumns(tb string) (cols []string)
	GetIndexes(tb string) (idxs []string)
	CreateTable(tb string, cols []Column) error
	AlterTable(tb string, cols []Column, unsafe bool) error
	OnConflictUpdate(tb string, cols []string) string
	UpdateWithLimit() bool
	ReplaceInto(src, dst string) error
}

Dialect :

func GetDialect

func GetDialect(driver string) (d Dialect, isValid bool)

GetDialect :

type Filter

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

Filter :

func (Filter) Field

func (f Filter) Field() string

Field :

func (*Filter) Interface

func (f *Filter) Interface() (interface{}, error)

Interface :

func (Filter) IsJSON

func (f Filter) IsJSON() bool

IsJSON :

func (Filter) JSON

func (f Filter) JSON() *JSON

JSON :

type Iterator

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

Iterator :

func (Iterator) Count

func (it Iterator) Count() uint

Count : return the records count

func (*Iterator) Cursor

func (it *Iterator) Cursor() (Cursor, error)

Cursor :

func (*Iterator) First

func (it *Iterator) First() *Iterator

First :

func (Iterator) Get

func (it Iterator) Get(k string) []byte

Get : get value by key

func (*Iterator) Last

func (it *Iterator) Last() *Iterator

Last :

func (*Iterator) Next

func (it *Iterator) Next() bool

Next : go next record

func (*Iterator) Scan

func (it *Iterator) Scan(src interface{}) error

Scan : set the model value

type JSON

type JSON struct {
}

JSON :

type Loader

type Loader interface {
	Load() error
}

Loader :

type LogHandler

type LogHandler func(*Stmt)

LogHandler :

type OmitDefault

type OmitDefault interface{}

OmitDefault :

type Pagination

type Pagination struct {
	Cursor string
	Limit  uint
	// contains filtered or unexported fields
}

Pagination :

func (*Pagination) Count

func (p *Pagination) Count() uint

Count : record count in this pagination record set

func (*Pagination) NextCursor

func (p *Pagination) NextCursor() string

NextCursor : next record set cursor

func (*Pagination) Reset

func (p *Pagination) Reset()

Reset : reset all the value in pagination to default value

func (*Pagination) SetQuery

func (p *Pagination) SetQuery(q *Query)

SetQuery :

type Property

type Property struct {
	Value interface{}
	// contains filtered or unexported fields
}

Property :

func (Property) Interface

func (p Property) Interface() (interface{}, error)

Interface :

func (Property) Name

func (p Property) Name() string

Name :

type Query

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

Query :

func (*Query) Ancestor

func (q *Query) Ancestor(ancestor *datastore.Key) *Query

Ancestor :

func (*Query) AnyOfAncestor

func (q *Query) AnyOfAncestor(ancestors ...*datastore.Key) *Query

AnyOfAncestor :

func (*Query) DistinctOn

func (q *Query) DistinctOn(fields ...string) *Query

DistinctOn :

func (*Query) Find

func (q *Query) Find(key *datastore.Key, model interface{}) error

Find :

func (*Query) First

func (q *Query) First(model interface{}) error

First :

func (*Query) Flush

func (q *Query) Flush() error

Flush :

func (*Query) Get

func (q *Query) Get(model interface{}) error

Get :

func (*Query) InsertInto

func (q *Query) InsertInto(table string) error

InsertInto :

func (*Query) Limit

func (q *Query) Limit(limit int) *Query

Limit :

func (*Query) Lock

func (q *Query) Lock(mode locked) *Query

Lock :

func (*Query) MatchAgainst added in v0.5.0

func (q *Query) MatchAgainst(fields []string, values ...string) *Query

MatchAgainst :

func (*Query) Offset

func (q *Query) Offset(offset int) *Query

Offset :

func (*Query) Omit

func (q *Query) Omit(fields ...string) *Query

Omit :

func (*Query) OrderBy added in v0.3.0

func (q *Query) OrderBy(values ...interface{}) *Query

OrderBy : OrderBy(expr.Field("Status", []string{}))

func (*Query) Paginate

func (q *Query) Paginate(p *Pagination, model interface{}) error

Paginate :

func (*Query) RLock

func (q *Query) RLock() *Query

RLock :

func (*Query) ReplaceInto

func (q *Query) ReplaceInto(table string) error

ReplaceInto :

func (*Query) Scan

func (q *Query) Scan(dest ...interface{}) error

Scan :

func (*Query) Select

func (q *Query) Select(fields ...string) *Query

Select :

func (*Query) Unscoped

func (q *Query) Unscoped() *Query

Unscoped :

func (*Query) Update

func (q *Query) Update(v interface{}) error

Update :

func (*Query) WLock

func (q *Query) WLock() *Query

WLock :

func (*Query) Where

func (q *Query) Where(field string, op string, value interface{}) *Query

Where :

func (*Query) WhereAnyLike

func (q *Query) WhereAnyLike(field string, v interface{}) *Query

WhereAnyLike :

func (*Query) WhereEqual

func (q *Query) WhereEqual(field string, v interface{}) *Query

WhereEqual :

func (*Query) WhereIn

func (q *Query) WhereIn(field string, v interface{}) *Query

WhereIn :

func (*Query) WhereJSON

func (q *Query) WhereJSON(field, op string, v interface{}) *Query

WhereJSON :

func (*Query) WhereJSONContainAny

func (q *Query) WhereJSONContainAny(field string, v interface{}) *Query

WhereJSONContainAny :

func (*Query) WhereJSONEqual

func (q *Query) WhereJSONEqual(field string, v interface{}) *Query

WhereJSONEqual :

func (*Query) WhereJSONIn

func (q *Query) WhereJSONIn(field string, v []interface{}) *Query

WhereJSONIn :

func (*Query) WhereJSONIsArray

func (q *Query) WhereJSONIsArray(field string) *Query

WhereJSONIsArray :

func (*Query) WhereJSONIsObject

func (q *Query) WhereJSONIsObject(field string) *Query

WhereJSONIsObject :

func (*Query) WhereJSONNotEqual

func (q *Query) WhereJSONNotEqual(field string, v interface{}) *Query

WhereJSONNotEqual :

func (*Query) WhereJSONNotIn

func (q *Query) WhereJSONNotIn(field string, v []interface{}) *Query

WhereJSONNotIn :

func (*Query) WhereJSONType

func (q *Query) WhereJSONType(field, typ string) *Query

WhereJSONType :

func (*Query) WhereLike

func (q *Query) WhereLike(field, v string) *Query

WhereLike :

func (*Query) WhereNotEqual

func (q *Query) WhereNotEqual(field string, v interface{}) *Query

WhereNotEqual :

func (*Query) WhereNotIn

func (q *Query) WhereNotIn(field string, v interface{}) *Query

WhereNotIn :

func (*Query) WhereNotLike

func (q *Query) WhereNotLike(field, v string) *Query

WhereNotLike :

func (*Query) WhereNotNull

func (q *Query) WhereNotNull(field string) *Query

WhereNotNull :

func (*Query) WhereNull

func (q *Query) WhereNull(field string) *Query

WhereNull :

type QueryBuilder added in v0.4.1

type QueryBuilder struct {
}

QueryBuilder :

type Registry added in v0.3.0

type Registry struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func NewRegistry added in v0.3.0

func NewRegistry() *Registry

func (*Registry) EncodeValue added in v0.3.0

func (r *Registry) EncodeValue(v reflect.Value) (interface{}, error)

func (*Registry) SetDefaultEncoders added in v0.3.0

func (r *Registry) SetDefaultEncoders()

func (*Registry) SetKindEncoder added in v0.3.0

func (r *Registry) SetKindEncoder(k reflect.Kind, f encodeFunc)

func (*Registry) SetTypeEncoder added in v0.3.0

func (r *Registry) SetTypeEncoder(t reflect.Type, f encodeFunc)

type Replacer

type Replacer interface {
	Upsert(model interface{}, k ...*datastore.Key) error
	Save(model interface{}) error
}

Replacer :

type Saver

type Saver interface {
	Save() error
}

Saver :

type Schema

type Schema struct {
	Name         string
	DataType     string
	DefaultValue interface{}
	IsUnsigned   bool
	IsNullable   bool
	IsIndexed    bool
	CharSet
}

Schema :

func (Schema) IsOmitEmpty

func (s Schema) IsOmitEmpty() bool

IsOmitEmpty :

type SoftDelete

type SoftDelete *time.Time

SoftDelete :

type Stmt

type Stmt struct {
	Result sql.Result
	// contains filtered or unexported fields
}

Stmt :

func (Stmt) Arguments

func (s Stmt) Arguments() []interface{}

Arguments :

func (*Stmt) Raw

func (s *Stmt) Raw() string

Raw :

func (*Stmt) String

func (s *Stmt) String() string

String :

func (Stmt) TimeElapse

func (s Stmt) TimeElapse() time.Duration

TimeElapse :

type StmtRegistry added in v0.3.0

type StmtRegistry struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func NewStmtRegistry added in v0.3.0

func NewStmtRegistry() *StmtRegistry

func (*StmtRegistry) BuildStatement added in v0.3.0

func (r *StmtRegistry) BuildStatement(w Writer, v reflect.Value) ([]interface{}, error)

func (*StmtRegistry) SetDefaultEncoders added in v0.3.0

func (r *StmtRegistry) SetDefaultEncoders()

func (*StmtRegistry) SetKindEncoder added in v0.3.0

func (r *StmtRegistry) SetKindEncoder(k reflect.Kind, f writerFunc)

func (*StmtRegistry) SetTypeEncoder added in v0.3.0

func (r *StmtRegistry) SetTypeEncoder(t reflect.Type, f writerFunc)

type StructCodec

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

StructCodec :

type Table

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

Table :

func (*Table) AddIndex

func (t *Table) AddIndex(fields ...string) error

AddIndex :

func (*Table) AddUniqueIndex

func (t *Table) AddUniqueIndex(fields ...string) error

AddUniqueIndex :

func (*Table) Ancestor

func (t *Table) Ancestor(ancestor *datastore.Key) *Query

Ancestor :

func (*Table) AnyOfAncestor

func (t *Table) AnyOfAncestor(ancestors ...*datastore.Key) *Query

AnyOfAncestor :

func (*Table) Create

func (t *Table) Create(model interface{}, parentKey ...*datastore.Key) error

Create :

func (*Table) DistinctOn

func (t *Table) DistinctOn(fields ...string) *Query

DistinctOn :

func (*Table) DropIfExists

func (t *Table) DropIfExists() error

DropIfExists :

func (*Table) Exists

func (t *Table) Exists() bool

Exists :

func (*Table) Find

func (t *Table) Find(key *datastore.Key, model interface{}) error

Find :

func (*Table) First

func (t *Table) First(model interface{}) error

First :

func (*Table) Get

func (t *Table) Get(model interface{}) error

Get :

func (*Table) InsertInto

func (t *Table) InsertInto(table string) error

InsertInto :

func (*Table) Limit

func (t *Table) Limit(limit int) *Query

Limit :

func (*Table) Lock

func (t *Table) Lock(mode locked) *Query

Lock :

func (*Table) Migrate

func (t *Table) Migrate(model interface{}) error

Migrate :

func (*Table) Offset

func (t *Table) Offset(offset int) *Query

Offset :

func (*Table) Omit

func (t *Table) Omit(fields ...string) *Query

Omit :

func (*Table) OrderBy added in v0.3.0

func (t *Table) OrderBy(fields ...interface{}) *Query

OrderBy :

func (*Table) Paginate

func (t *Table) Paginate(p *Pagination, model interface{}) error

Paginate :

func (*Table) RLock

func (t *Table) RLock() *Query

RLock :

func (*Table) ReplaceInto

func (t *Table) ReplaceInto(table string) error

ReplaceInto :

func (*Table) Save

func (t *Table) Save(model interface{}) error

Save :

func (*Table) Scan

func (t *Table) Scan(dest ...interface{}) error

Scan :

func (*Table) Select

func (t *Table) Select(fields ...string) *Query

Select :

func (*Table) Truncate

func (t *Table) Truncate() error

Truncate :

func (*Table) Unscoped

func (t *Table) Unscoped() *Query

Unscoped :

func (*Table) Update

func (t *Table) Update(v interface{}) error

Update :

func (*Table) Upsert

func (t *Table) Upsert(model interface{}, parentKey ...*datastore.Key) error

Upsert :

func (*Table) WLock

func (t *Table) WLock() *Query

WLock :

func (*Table) Where

func (t *Table) Where(field, op string, value interface{}) *Query

Where :

func (*Table) WhereEqual

func (t *Table) WhereEqual(field string, v interface{}) *Query

WhereEqual :

func (*Table) WhereIn

func (t *Table) WhereIn(field string, v []interface{}) *Query

WhereIn :

func (*Table) WhereJSONEqual

func (t *Table) WhereJSONEqual(field string, v interface{}) *Query

WhereJSONEqual :

func (*Table) WhereLike

func (t *Table) WhereLike(field, v string) *Query

WhereLike :

func (*Table) WhereNotEqual

func (t *Table) WhereNotEqual(field string, v interface{}) *Query

WhereNotEqual :

func (*Table) WhereNotIn

func (t *Table) WhereNotIn(field string, v []interface{}) *Query

WhereNotIn :

func (*Table) WhereNotLike

func (t *Table) WhereNotLike(field, v string) *Query

WhereNotLike :

func (*Table) WhereNotNull

func (t *Table) WhereNotNull(field string) *Query

WhereNotNull :

func (*Table) WhereNull

func (t *Table) WhereNull(field string) *Query

WhereNull :

type TransactionHandler

type TransactionHandler func(*DB) error

TransactionHandler :

type Writer added in v0.3.0

type Writer interface {
	io.Writer
	io.StringWriter
	io.ByteWriter
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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