gocqlx

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 25, 2018 License: Apache-2.0 Imports: 8 Imported by: 0

README

GoCQLX GoDoc Go Report Card Build Status

Package gocqlx is an idiomatic extension to gocql that provides usability features. With gocqlx you can bind the query parameters from maps and structs, use named query parameters (:identifier) and scan the query results into structs and slices. It comes with a fluent and flexible CQL query builder and a database migrations module.

Installation

go get -u github.com/scylladb/gocqlx

Features

  • Binding query parameters form struct or map
  • Scanning results directly into struct or slice
  • CQL query builder (see more)
  • Database migrations (see more)
  • Fast!

Example

// Field names are converted to camel case by default, no need to add
// `db:"first_name"`, if you want to disable a filed add `db:"-"` tag.
type Person struct {
    FirstName string
    LastName  string
    Email     []string
}

// Bind query parameters from a struct.
{
    p := Person{
        "Patricia",
        "Citizen",
        []string{"patricia.citzen@gocqlx_test.com"},
    }

    stmt, names := qb.Insert("gocqlx_test.person").
        Columns("first_name", "last_name", "email").
        ToCql()

    err := gocqlx.Query(session.Query(stmt), names).BindStruct(&p).ExecRelease()
    if err != nil {
        t.Fatal(err)
    }
}

// Load the first result into a struct.
{
    stmt, names := qb.Select("gocqlx_test.person").
        Where(qb.Eq("first_name")).
        ToCql()

    var p Person

    q := gocqlx.Query(session.Query(stmt), names).BindMap(qb.M{
        "first_name": "Patricia",
    })
    if err := q.GetRelease(&p); err != nil {
        t.Fatal(err)
    }
}

// Load all the results into a slice.
{
    stmt, names := qb.Select("gocqlx_test.person").
        Where(qb.In("first_name")).
        ToCql()

    var people []Person

    q := gocqlx.Query(session.Query(stmt), names).BindMap(qb.M{
        "first_name": []string{"Patricia", "Igy", "Ian"},
    })
    if err := q.SelectRelease(&people); err != nil {
        t.Fatal(err)
    }
}

// Use named query parameters.
{
    p := &Person{
        "Jane",
        "Citizen",
        []string{"jane.citzen@gocqlx_test.com"},
    }

    stmt, names, err := gocqlx.CompileNamedQuery([]byte("INSERT INTO gocqlx_test.person (first_name, last_name, email) VALUES (:first_name, :last_name, :email)"))
    if err != nil {
        t.Fatal(err)
    }

    err = gocqlx.Query(session.Query(stmt), names).BindStruct(p).ExecRelease()
    if err != nil {
        t.Fatal(err)
    }
}

See more examples in example_test.go.

Performance

Gocqlx is fast, this is a benchmark result comparing gocqlx to raw gocql on a local machine, Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz.

BenchmarkE2EGocqlInsert-4         500000            258434 ns/op            2627 B/op         59 allocs/op
BenchmarkE2EGocqlxInsert-4       1000000            120257 ns/op            1555 B/op         34 allocs/op
BenchmarkE2EGocqlGet-4           1000000            131424 ns/op            1970 B/op         55 allocs/op
BenchmarkE2EGocqlxGet-4          1000000            131981 ns/op            2322 B/op         58 allocs/op
BenchmarkE2EGocqlSelect-4          30000           2588562 ns/op           34605 B/op        946 allocs/op
BenchmarkE2EGocqlxSelect-4         30000           2637187 ns/op           27718 B/op        951 allocs/op

See the benchmark in benchmark_test.go.

License

Copyright (C) 2017 ScyllaDB

This project is distributed under the Apache 2.0 license. See the LICENSE file for details. It contains software from:

Apache®, Apache Cassandra® are either registered trademarks or trademarks of the Apache Software Foundation in the United States and/or other countries. No endorsement by The Apache Software Foundation is implied by the use of these marks.

GitHub star is always appreciated!

Documentation

Overview

Package gocqlx is an idiomatic extension to gocql that provides usability features. With gocqlx you can bind the query parameters from maps and structs, use named query parameters (:identifier) and scan the query results into structs and slices. It comes with a fluent and flexible CQL query builder and a database migrations module.

Index

Constants

This section is empty.

Variables

View Source
var DefaultMapper = reflectx.NewMapperFunc("db", snakeCase)

DefaultMapper uses `db` tag and automatically converts struct field names to snake case. It can be set to whatever you want, but it is encouraged to be set before gocqlx is used as name-to-field mappings are cached after first use on a type.

Functions

func CompileNamedQuery

func CompileNamedQuery(qs []byte) (stmt string, names []string, err error)

CompileNamedQuery compiles a named query into an unbound query using the '?' bindvar and a list of names.

func Get

func Get(dest interface{}, q *gocql.Query) error

Get is a convenience function for creating iterator and calling Get.

DEPRECATED use Queryx.Get or Queryx.GetRelease.

func Select

func Select(dest interface{}, q *gocql.Query) error

Select is a convenience function for creating iterator and calling Select.

DEPRECATED use Queryx.Select or Queryx.SelectRelease.

Types

type Iterx

type Iterx struct {
	*gocql.Iter

	Mapper *reflectx.Mapper
	// contains filtered or unexported fields
}

Iterx is a wrapper around gocql.Iter which adds struct scanning capabilities.

func Iter

func Iter(q *gocql.Query) *Iterx

Iter creates a new Iterx from gocql.Query using a default mapper.

func (*Iterx) Close

func (iter *Iterx) Close() error

Close closes the iterator and returns any errors that happened during the query or the iteration.

func (*Iterx) Get

func (iter *Iterx) Get(dest interface{}) error

Get scans first row into a destination and closes the iterator. If the destination type is a struct pointer, then StructScan will be used. If the destination is some other type, then the row must only have one column which can scan into that type.

If no rows were selected, ErrNotFound is returned.

func (*Iterx) Select

func (iter *Iterx) Select(dest interface{}) error

Select scans all rows into a destination, which must be a pointer to slice of any type and closes the iterator. If the destination slice type is a struct, then StructScan will be used on each row. If the destination is some other type, then each row must only have one column which can scan into that type.

If no rows were selected, ErrNotFound is NOT returned.

func (*Iterx) StructScan

func (iter *Iterx) StructScan(dest interface{}) bool

StructScan is like gocql.Iter.Scan, but scans a single row into a single struct. Use this and iterate manually when the memory load of Select() might be prohibitive. StructScan caches the reflect work of matching up column positions to fields to avoid that overhead per scan, which means it is not safe to run StructScan on the same Iterx instance with different struct types.

func (*Iterx) Unsafe

func (iter *Iterx) Unsafe() *Iterx

Unsafe forces the iterator to ignore missing fields. By default when scanning a struct if result row has a column that cannot be mapped to any destination field an error is reported. With unsafe such columns are ignored.

type Queryx

type Queryx struct {
	*gocql.Query
	Names  []string
	Mapper *reflectx.Mapper
	// contains filtered or unexported fields
}

Queryx is a wrapper around gocql.Query which adds struct binding capabilities.

func Query

func Query(q *gocql.Query, names []string) *Queryx

Query creates a new Queryx from gocql.Query using a default mapper.

func (*Queryx) BindMap

func (q *Queryx) BindMap(arg map[string]interface{}) *Queryx

BindMap binds query named parameters using map.

func (*Queryx) BindStruct

func (q *Queryx) BindStruct(arg interface{}) *Queryx

BindStruct binds query named parameters to values from arg using mapper. If value cannot be found error is reported.

func (*Queryx) BindStructMap

func (q *Queryx) BindStructMap(arg0 interface{}, arg1 map[string]interface{}) *Queryx

BindStructMap binds query named parameters to values from arg0 and arg1 using a mapper. If value cannot be found in arg0 it's looked up in arg1 before reporting an error.

func (*Queryx) Err

func (q *Queryx) Err() error

Err returns any binding errors.

func (*Queryx) Exec

func (q *Queryx) Exec() error

Exec executes the query without returning any rows.

func (*Queryx) ExecRelease

func (q *Queryx) ExecRelease() error

ExecRelease calls Exec and releases the query, a released query cannot be reused.

func (*Queryx) Get

func (q *Queryx) Get(dest interface{}) error

Get scans first row into a destination. If the destination type is a struct pointer, then Iter.StructScan will be used. If the destination is some other type, then the row must only have one column which can scan into that type.

If no rows were selected, ErrNotFound is returned.

func (*Queryx) GetRelease

func (q *Queryx) GetRelease(dest interface{}) error

GetRelease calls Get and releases the query, a released query cannot be reused.

func (*Queryx) Select

func (q *Queryx) Select(dest interface{}) error

Select scans all rows into a destination, which must be a pointer to slice of any type. If the destination slice type is a struct, then Iter.StructScan will be used on each row. If the destination is some other type, then each row must only have one column which can scan into that type.

If no rows were selected, ErrNotFound is NOT returned.

func (*Queryx) SelectRelease

func (q *Queryx) SelectRelease(dest interface{}) error

SelectRelease calls Select and releases the query, a released query cannot be reused.

Directories

Path Synopsis
Package migrate provides simple and flexible CLQ migrations.
Package migrate provides simple and flexible CLQ migrations.
Package qb provides CQL query builders.
Package qb provides CQL query builders.
Package reflectx implements extensions to the standard reflect lib suitable for implementing marshalling and unmarshalling packages.
Package reflectx implements extensions to the standard reflect lib suitable for implementing marshalling and unmarshalling packages.

Jump to

Keyboard shortcuts

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