Conditionals

Conditionals are restrictions of where clause in qb. There are many conditional builders inside the WhereClause.

The following initializations are assumed;

package main

import (
	"fmt"
	"github.com/aacanakin/qb"
)

func main() {
	db, _ := qb.New("sqlite3", ":memory:")
	defer db.Close()

	db.Dialect().SetEscaping(true)

	actors := qb.Table(
		"actor",
		qb.Column("id", qb.Varchar().Size(36)),
		qb.Column("name", qb.Varchar().NotNull()),
		qb.Column("nomination_count", qb.Int().Default(0)),
		qb.Column("oscar_count", qb.Int().Default(0)),
		qb.PrimaryKey("id"),
	)

}

A typical Select ... Where ... clause is build by conditionals especially inside the where clause. In this example, you can reach the column object by users.C("column-name"). The conditionals can be generated.

A simple Select ... Where ... using Conditionals would be the following;

sel := actors.
		Select(actors.C("name")).
		Where(actors.C("nomination_count").Gt(0)).
		Build(db.Dialect())

fmt.Println(sel.SQL())
fmt.Println(sel.Bindings())

Here, the query asks db where nomination_count field is greater than 0. Output is;

SELECT name
FROM actor
WHERE actor.nomination_count > ?;
[0]

The ">" character builder here is the Gt() function inside the ColumnElem object.

Here is the full list of conditionals;

ConditionalDescription
Like(pattern string)Builds a LIKE conditional using pattern such as %user%
NotIn(values ...interface{})Builds a NOT IN(...) conditional given values such as "[email protected]", "[email protected]"
In(values ...interface{})Builds an IN(...) conditional given values such as "[email protected]", "[email protected]"
NotEq(value interface{})Builds a :var != :placeholder conditional given value.
Eq(value interface{})Builds a :var = :placeholder conditional given value.
Gt(value interface{})Builds a :var > :placeholder conditional given value.
Gte(value interface{})Builds a :var >= :placeholder conditional given value.
St(value interface{})Builds a :var < :placeholder conditional given value.
Ste(value interface{})Builds a :var <= :placeholder conditional given value.

You can also build custom Conditionals using Condition(col ColumnElem, op string, values ...interface{}) function.