Categorygithub.com/orus-io/qb
modulepackage
0.0.0-20231123162623-2cb2d8b29f15
Repository: https://github.com/orus-io/qb.git
Documentation: pkg.go.dev

# README

alt text

qb - the database toolkit for go

Build Status Coverage Status License (LGPL version 2.1) Go Report Card GoDoc

This project is currently pre 1.

Currently, it's not feature complete. It can have potential bugs. There are no tests covering concurrency race conditions. It can crash especially in concurrency. Before 1.x releases, each major release could break backwards compatibility.

About qb

qb is a database toolkit for easier db queries in go. It is inspired from python's best orm, namely sqlalchemy. qb is an orm(sqlx) as well as a query builder. It is quite modular in case of using just expression api and query building stuff.

Documentation

The documentation is hosted in readme.io which has great support for markdown docs. Currently, the docs are about 80% - 90% complete. The doc files will be added to this repo soon. Moreover, you can check the godoc from here. Contributions & Feedbacks in docs are welcome.

Features

  • Support for postgres(9.5.+), mysql & sqlite3
  • Powerful expression API for building queries & table ddls
  • Struct to table ddl mapper where initial table migrations can happen
  • Transactional session api that auto map structs to queries
  • Foreign key definitions
  • Single & Composite column indices
  • Relationships (soon.. probably in 0.3 milestone)

Installation

go get -u github.com/slicebit/qb

If you want to install test dependencies then;

go get -u -t github.com/slicebit/qb

Quick Start

package main

import (
	"fmt"
	"github.com/slicebit/qb"
	_ "github.com/mattn/go-sqlite3"
    _ "github.com/slicebit/qb/dialects/sqlite"
)

type User struct {
	ID       string `db:"id"`
	Email    string `db:"email"`
	FullName string `db:"full_name"`
	Oscars   int    `db:"oscars"`
}

func main() {

	users := qb.Table(
		"users",
		qb.Column("id", qb.Varchar().Size(40)),
		qb.Column("email", qb.Varchar()).NotNull().Unique(),
		qb.Column("full_name", qb.Varchar()).NotNull(),
		qb.Column("oscars", qb.Int()).NotNull().Default(0),
		qb.PrimaryKey("id"),
	)

	db, err := qb.New("sqlite3", "./qb_test.db")
	if err != nil {
		panic(err)
	}

	defer db.Close()

	metadata := qb.MetaData()

	// add table to metadata
	metadata.AddTable(users)

	// create all tables registered to metadata
	metadata.CreateAll(db)
	defer metadata.DropAll(db) // drops all tables

	ins := qb.Insert(users).Values(map[string]interface{}{
		"id":        "b6f8bfe3-a830-441a-a097-1777e6bfae95",
		"email":     "[email protected]",
		"full_name": "Jack Nicholson",
	})

	_, err = db.Exec(ins)
	if err != nil {
		panic(err)
	}

	// find user
	var user User

	sel := qb.Select(users.C("id"), users.C("email"), users.C("full_name")).
		From(users).
		Where(users.C("id").Eq("b6f8bfe3-a830-441a-a097-1777e6bfae95"))

	err = db.Get(sel, &user)
	fmt.Printf("%+v\n", user)
}

Credits

# Packages

No description provided by the author

# Functions

Aggregate generates a new aggregate clause given function & clause.
Alias returns a new AliasClause.
And generates an AndClause given conditional clauses.
Avg function generates "avg(%s)" statement for clause.
BigInt creates bigint type.
BinaryExpression generates a condition object to use in update, delete & select statements.
Bind a value.
Blob creates a BLOB type.
Boolean creates boolean type.
Char creates char type.
Column generates a ColumnElem given name and type.
Constraint generates a custom constraint due to variation of dialects.
Count function generates "count(%s)" statement for clause.
Decimal creates a decimal type.
Default generates generic default constraint.
DefaultCompileType is a default implementation for Dialect.CompileType.
Delete generates a delete statement and returns it for chaining qb.Delete(usersTable).Where(qb.Eq("id", 5)).
Eq generates a equals conditional sql clause.
EscapeAll common escape all.
Exists returns a EXISTS clause.
Float creates float type.
ForeignKey generates a foreign key for table constraint definitions.
GetClauseFrom returns the value if already a Clause, or make one if it is a scalar value.
GetListFrom returns a list clause from any list If only one value is passed and is a ListClause, it is returned as-is.
Gt generates a greater than conditional sql clause.
Gte generates a greater than or equal to conditional sql clause.
GuessJoinOnClause finds a join 'ON' clause between two tables.
In generates an IN conditional sql clause.
Index generates an index clause given table and columns as params.
Insert generates an insert statement and returns it Insert(usersTable).Values(map[string]interface{}{"id": 1}).
Int creates int type.
Join returns a new JoinClause onClause can be one of: - 0 clause: attempt to guess the join clause (only if left & right are tables), otherwise panics - 1 clause: use it directly - 2 clauses: use a Eq() of both.
Like generates a like conditional sql clause.
List returns a list-of-clauses clause.
Lt generates a less than conditional sql clause.
Lte generates a less than or equal to conditional sql clause.
MakeJoinOnClause assemble a 'ON' clause for a join from either: 0 clause: attempt to guess the join clause (only if left & right are tables), otherwise panics 1 clause: returns it 2 clauses: returns a Eq() of both otherwise if panics.
Max function generates "max(%s)" statement for clause.
MetaData creates a new MetaData object and returns it as a pointer.
Min function generates "min(%s)" statement for clause.
New generates a new engine and returns it as an engine pointer.
NewCompilerContext initialize a new compiler context.
NewDefaultDialect instanciate a DefaultDialect.
NewDialect returns a dialect pointer given driver.
NewSQLCompiler returns a new SQLCompiler.
NotEq generates a not equal conditional sql clause.
NotExists returns a NOT EXISTS clause.
NotIn generates an NOT IN conditional sql clause.
NotNull generates generic not null constraint.
Null generates generic null constraint.
Numeric creates a numeric type.
Or generates an AndClause given conditional clauses.
PrimaryKey generates a primary key constraint of any table.
RegisterDialect add a new dialect to the registry.
Select generates a select statement and returns it.
SmallInt creates smallint type.
SQLText returns a raw SQL clause.
Statement creates a new query and returns its pointer.
Sum function generates "sum(%s)" statement for clause.
Table generates table struct given name and clauses.
Text creates text type.
Timestamp creates timestamp type.
TinyInt creates tinyint type.
Type returns a new TypeElem while defining columns in table.
Unique generates generic unique constraint if cols are given, then composite unique constraint will be built.
UniqueKey generates UniqueKeyConstraint given columns as strings.
Update generates an update statement and returns it qb.Update(usersTable).
Upsert generates an insert ..
UUID creates a UUID type.
Varchar creates varchar type.
Where generates a compilable where clause.

# Constants

ErrAny is for errors that could not be categorized by the dialect.
ErrData is for errors that are due to problems with the processed data like division by zero, numeric value out of range, etc.
ErrDatabase is a bit mask for errors that are related to the database.
ErrIntegrity is when the relational integrity of the database is affected, e.g.
ErrInterface is a bit mask for errors that are related to the database interface rather than the database itself.
ErrInternal is when the database encounters an internal error, e.g.
ErrNotSupported is in case a method or database API was used which is not supported by the database, e.g.
ErrOperational is for errors that are related to the database's operation and not necessarily under the control of the programmer, e.g.
ErrProgramming is for programming errors, e.g.
LBindings Flag to log bindings.
LDefault is the default flag that logs nothing.
LQuery Flag to log queries.

# Variables

DialectRegistry is a global registry of dialects.

# Structs

AggregateClause is the base struct for building aggregate functions.
AliasClause is a ALIAS sql clause.
BinaryExpressionClause is the base struct for any conditional statements in sql clauses.
BindClause binds a value to a placeholder.
ColumnElem is the definition of any columns defined in a table.
ColumnOptions holds options for a column.
CombinerClause is for OR and AND clauses.
CompilerContext is a data structure passed to all the Compiler visit functions.
ConstraintElem is the definition of column & table constraints.
DefaultDialect is a type of dialect that can be used with unsupported sql drivers.
DefaultLogger is the default logger of qb engine unless engine.SetLogger() is not called.
DeleteStmt is the base struct for building delete queries.
Engine is the generic struct for handling db connections.
Error wraps driver errors.
ExistsClause is a EXISTS clause.
ForeignKeyConstraint is the main struct for defining foreign key references.
ForeignKeyConstraints is the definition of foreign keys in any table.
ForUpdateClause is a FOR UPDATE expression.
HavingClause is the base struct for generating having clauses when using select It satisfies SQLClause interface.
InClause is a IN or NOT IN binary expression.
IndexElem is the definition of any index elements for a table.
InsertStmt is the base struct for any insert statements.
JoinClause is the base struct for generating join clauses when using select It satisfies Clause interface.
ListClause is a list of clause elements (for IN operator for example).
MetaDataElem is the container for database structs and tables.
OrderByClause is the base struct for generating order by clauses when using select It satisfies SQLClause interface.
PrimaryKeyConstraint is the definition of primary key constraints of any table.
Row wraps a *sql.Row in order to translate errors.
SelectStmt is the base struct for building select statements.
SQLCompiler aims to provide a SQL ANSI-92 implementation of Compiler.
Stmt is the base abstraction for all sql queries.
TableElem is the definition of any sql table.
TextClause is a raw SQL clause.
Tx is an in-progress database transaction.
TypeElem is the struct for defining column types.
UniqueKeyConstraint is the base struct to define composite unique indexes of tables.
UpdateStmt is the base struct for any update statements.
UpsertStmt is the base struct for any insert ..
WhereClause is the base of any where clause when using expression api.

# Interfaces

Builder is the common interface for any statement builder in qb such as Insert(), Update(), Delete(), Select() query starters.
Clause is the base interface of all clauses that will get compiled to SQL by Compiler.
Compiler is a visitor that produce SQL from various types of Clause.
Dialect is the common interface for driver changes It is for fixing compatibility issues of different drivers.
Logger is the std logger interface of the qb engine.
Selectable is any clause from which we can select columns and is suitable as a FROM clause element.
TableSQLClause is the common interface for ddl generators such as Column(), PrimaryKey(), ForeignKey().Ref(), etc.

# Type aliases

CompositeIndex is the struct definition when building composite indices for any struct that will be mapped into a table.
ErrorCode discriminates the types of errors that qb wraps, mainly the constraint errors The different kind of errors are based on the python dbapi errors (https://www.python.org/dev/peps/pep-0249/#exceptions).
LogFlags is the type we use for flags that can be passed to the logger.