gocqlx

package module
v0.0.0-...-11bee42 Latest Latest
Warning

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

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

README

GoCQLX GoDoc Go Report Card Build Status

Package gocqlx is a productivity toolkit for ScyllaDB and Apache Cassandra®. It's an extension of gocql, similar to what sqlx is to database/sql.

It contains wrappers over gocql types that provide convenience methods which are useful in the development of database driven applications. Under the hood it uses sqlx/reflectx package so sqlx models will also work with gocqlx.

Installation

go get -u github.com/scylladb/gocqlx

Features

  • Builders for SELECT, INSERT, UPDATE DELETE and BATCH (supporting collections, counters and functions)
  • Queries with named parameters (:identifier) support
  • Binding parameters form struct or map
  • Scanning results into structs and slices
  • Automatic query releasing
  • Schema migrations
  • Fast!

Example

type Person struct {
    FirstName string  // no need to add `db:"first_name"` etc.
    LastName  string
    Email     []string
}

// Insert with query parameters bound from 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()

    q := gocqlx.Query(session.Query(stmt), names).BindStruct(p)

    if err := q.ExecRelease(); err != nil {
        t.Fatal(err)
    }
}

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

    q := gocqlx.Query(session.Query(stmt), names).BindMap(qb.M{
        "first_name": "Patricia",
    })

    var p Person
    if err := gocqlx.Get(&p, q.Query); err != nil {
        t.Fatal("get:", err)
    }

    t.Log(p)
    // {Patricia Citizen [patricia.citzen@gocqlx_test.com patricia1.citzen@gocqlx_test.com]}
}

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

    q := gocqlx.Query(session.Query(stmt), names).BindMap(qb.M{
        "first_name": []string{"Patricia", "Igy", "Ian"},
    })

    var people []Person
    if err := gocqlx.Select(&people, q.Query); err != nil {
        t.Fatal("select:", err)
    }

    t.Log(people)
    // [{Patricia Citizen [patricia.citzen@gocqlx_test.com patricia1.citzen@gocqlx_test.com]} {Igy Citizen [igy.citzen@gocqlx_test.com]} {Ian Citizen [ian.citzen@gocqlx_test.com]}]
}

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. For query binding (insert) gocqlx is faster then gocql thanks to smart caching, otherwise the performance is comparable.

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 a productivity toolkit for ScyllaDB and Apache Cassandra®. It's an extension of `gocql`, similar to what `sqlx` is to `database/sql`.

It contains wrappers over gocql types that provide convenience methods which are useful in the development of database driven applications. Under the hood it uses sqlx/reflectx package so sqlx models will also work with gocqlx.

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.

func Select

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

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

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, 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 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.

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 performs exec and releases the query, a released query cannot be reused.

Directories

Path Synopsis
Package migrate provides simple and flexible ScyllaDB and Apache Cassandra® migrations.
Package migrate provides simple and flexible ScyllaDB and Apache Cassandra® migrations.
Package qb provides CQL query builders.
Package qb provides CQL query builders.

Jump to

Keyboard shortcuts

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