litsql

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2024 License: MIT Imports: 1 Imported by: 5

README

litsql - Literal SQL query builder

litsql is a Golang string concatenation library disguised as an SQL query builder.

Ok, it really is an SQL query builder, but it aims to be an easier-to-use replacement for raw SQL strings.

Each litsql statement must be directly related to an SQL output, including whitespace, which must be obvious to the user of the library. The output will be exactly the passed values, so the library won't prevent invalid SQL from being generated.

The library tests includes testing for exact string and whitespace output to ensure this.

func ExampleSelect_literalSimple() {
    // SELECT
    q := psql.Select(
        // u.id, u.name
        sm.Columns("u.id", "u.name"),
        // , u.created_at, u.updated_at
        sm.Columns("u.created_at", "u.updated_at"),
        // FROM users As u
        sm.From("users AS u"),
        // WHERE u.age > $1
        sm.WhereC("u.age > ?", 40),
        // AND u.deleted_at IS NOT NULL
        sm.Where("u.deleted_at IS NOT NULL"),
        // ORDER BY u.name ASC, u.age DESC
        sm.OrderBy("u.name ASC", "u.age DESC"),
    )
    qs, args, err := q.Build()
    if err != nil {
        panic(err)
    }
    fmt.Println(qs)
    fmt.Println("===")
    fmt.Println(args)

    // Output:
    // SELECT u.id, u.name, u.created_at, u.updated_at
    // FROM users AS u
    // WHERE u.age > $1 AND u.deleted_at IS NOT NULL
    // ORDER BY u.name ASC, u.age DESC
    // ===
    // [40]
}

The library will do:

  • ensure clause ordering

The library won't do:

  • prevent invalid SQL from being output
  • automatic quoting

Installation

go get -u github.com/rrgmc/litsql

Examples

func ExampleSelect_literalJoin() {
    // SELECT
    q := psql.Select(
        // orders.id as order_id, orders.date
        sm.Columns("orders.id AS order_id", "orders.date"),
        // u.id AS user_id, u.name as user_name
        sm.Columns("u.id AS user_id", "u.name AS user_name"),
        // FROM orders
        sm.From("orders"),
        // INNER JOIN users AS u ON orders.user_id = u.id
        sm.InnerJoin("users AS u").On("orders.user_id = u.id"),
        // WHERE u.age > $1
        sm.WhereC("u.age ?",
            // example to use either IS NULL or a comparison
            expr.ExprIfElse(true, // some condition
                expr.C("> ?", 32),
                expr.S("IS NULL"))),
        // AND u.deleted_at IS NOT NULL
        sm.Where("u.deleted_at IS NOT NULL"),
        // ORDER BY order.date DESC, u.name ASC
        sm.OrderBy("orders.date DESC", "u.name ASC"),
    )
    qs, args, err := q.Build()
    if err != nil {
        panic(err)
    }
    fmt.Println(qs)
    fmt.Println("===")
    fmt.Println(args)

    // Output:
    // SELECT orders.id AS order_id, orders.date, u.id AS user_id, u.name AS user_name
    // FROM orders
    // INNER JOIN users AS u ON orders.user_id = u.id
    // WHERE u.age > $1 AND u.deleted_at IS NOT NULL
    // ORDER BY orders.date DESC, u.name ASC
    // ===
    // [32]
}
func ExampleSelect_literalWith() {
    q := psql.Select(
        // WITH regional_sales AS (
        sm.With("regional_sales").As(
            // SELECT
            psql.Select(
                // region, SUM(amount) AS total_sales
                sm.Columns("region", "SUM(amount) AS total_sales"),
                // FROM orders
                sm.From("orders"),
                // GROUP BY region
                sm.GroupBy("region"),
            ),
        ),
        // ), top_regions AS (
        sm.With("top_regions").As(
            // SELECT
            psql.Select(
                // region
                sm.Columns("region"),
                // FROM regional_sales
                sm.From("regional_sales"),
                // WHERE total_sales > (SELECT SUM(total_sales)/10 FROM regional_sales)
                sm.WhereC("total_sales > ?",
                    psql.Select(
                        sm.Columns("SUM(total_sales)/10"),
                        sm.From("regional_sales"),
                    ),
                ),
            ),
        ),
        // )
        // SELECT
        // region, product, SUM(quantity) AS product_units, SUM(amount) AS product_sales
        sm.Columns("region", "product", "SUM(quantity) AS product_units", "SUM(amount) AS product_sales"),
        // FROM orders
        sm.From("orders"),
        // WHERE region IN (SELECT region FROM top_regions)
        sm.WhereC("region IN ?",
            psql.Select(
                sm.Columns("region"),
                sm.From("top_regions"),
            ),
        ),
        // GROUP BY region, product
        sm.GroupBy("region", "product"),
    )
    qs, _, err := q.Build()
    if err != nil {
        panic(err)
    }
    fmt.Println(qs)

    // Output:
    // WITH regional_sales AS (
    //   SELECT region, SUM(amount) AS total_sales
    //   FROM orders
    //   GROUP BY region
    // ),
    // top_regions AS (
    //   SELECT region
    //   FROM regional_sales
    //   WHERE total_sales > (
    //     SELECT SUM(total_sales)/10
    //     FROM regional_sales
    //   )
    // )
    // SELECT region, product, SUM(quantity) AS product_units, SUM(amount) AS product_sales
    // FROM orders
    // WHERE region IN (
    //   SELECT region
    //   FROM top_regions
    // )
    // GROUP BY region, product
}

Reference

This library is heavily inspired by the excellent Bob Go SQL Access Toolkit. Its base ideas and some of its implementations where used to build this library's interface.

The biggest difference is that Bob is not only a query builder, but an ORM, so the query builder part must be much more complex to be able to tackle multiple jobs. In some parts it is hard to directly relate what SQL will be generated, and it encourages using Go to code SQL expressions, which this library heavily discourages.

Author

Rangel Reale (rangelreale@gmail.com)

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrClause = errors.New("clause error")
)

Functions

func Express

func Express(w Writer, d Dialect, start int, e Expression) ([]any, error)

func ExpressIf

func ExpressIf(w Writer, d Dialect, start int, e Expression, cond bool, prefix, suffix Expression) ([]any, error)

ExpressIf expands an express if the condition evaluates to true it can also add a prefix and suffix

func ExpressSlice

func ExpressSlice(w Writer, d Dialect, start int, expressions []Expression, prefix, sep, suffix Expression) ([]any, error)

ExpressSlice is used to express a slice of expressions along with a prefix and suffix

Types

type Argument

type Argument interface {
	// contains filtered or unexported methods
}

Argument is the base interface for query arguments.

type ArgumentBase

type ArgumentBase struct{}

type DBNamedArgument

type DBNamedArgument interface {
	Argument
	DBName() string
}

DBNamedArgument is like NamedArgument but its value will be wrapped using [sql.Named].

type Dialect

type Dialect interface {
	WriteArg(w Writer, position int)
	WriteQuoted(w Writer, s string)
	WriteCheckQuoted(w Writer, s string)
}

Dialect implements dialect-specific methods.

type DialectWithNamed

type DialectWithNamed interface {
	Dialect
	WriteNamedArg(w Writer, name string)
}

DialectWithNamed implements dialects that support db-specific named arguments.

type ExpressBuilder

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

ExpressBuilder builds arguments in a sequence of Express calls.

func NewExpressBuilder

func NewExpressBuilder(w Writer, d Dialect, start int) *ExpressBuilder

func (*ExpressBuilder) Err

func (h *ExpressBuilder) Err() error

func (*ExpressBuilder) Express

func (h *ExpressBuilder) Express(e Expression)

func (*ExpressBuilder) ExpressIf

func (h *ExpressBuilder) ExpressIf(e Expression, cond bool, prefix, suffix Expression)

func (*ExpressBuilder) ExpressSlice

func (h *ExpressBuilder) ExpressSlice(expressions []Expression, prefix, sep, suffix Expression)

func (*ExpressBuilder) Result

func (h *ExpressBuilder) Result() ([]any, error)

func (*ExpressBuilder) WriteQuery

func (h *ExpressBuilder) WriteQuery(e Query)

type Expression

type Expression interface {
	WriteSQL(w Writer, d Dialect, start int) (args []any, err error)
}

Expression is the base expression interface.

type ExpressionFunc

type ExpressionFunc func(w Writer, d Dialect, start int) ([]any, error)

ExpressionFunc is the functional implementation of Expression.

func (ExpressionFunc) WriteSQL

func (e ExpressionFunc) WriteSQL(w Writer, d Dialect, start int) ([]any, error)

type NamedArgument

type NamedArgument interface {
	Argument
	Name() string
}

NamedArgument represents an argument were its value will be provided by name.

type Query

type Query interface {
	Expression
	WriteQuery(w Writer, start int) (args []any, err error)
}

Query is the base interface for queries.

type QueryBuilder

type QueryBuilder interface {
	Dialect() Dialect
	AddQueryClause(q QueryClause)
}

QueryBuilder is the base interface for queries built by lists of clauses.

type QueryClause

type QueryClause interface {
	Expression
	ClauseID() string
	ClauseOrder() int
}

QueryClause is a query clause.

type QueryClauseMerge

type QueryClauseMerge interface {
	QueryClause
	ClauseMerge(other QueryClause) error
}

QueryClauseMerge can be implemented by QueryClause when its data can be merged.

type QueryClauseMultiple

type QueryClauseMultiple interface {
	QueryClause
	ClauseMultiple()
}

QueryClauseMultiple can be implemented by QueryClause to signal multiple instances can be added.

type QueryFunc added in v0.3.2

type QueryFunc struct {
	D Dialect
	E Expression
	F func(w Writer, start int) (args []any, err error) // if nil, WriteSQL will be called directly.
}

QueryFunc is a functional implementation of Query.

func (QueryFunc) WriteQuery added in v0.3.2

func (q QueryFunc) WriteQuery(w Writer, start int) (args []any, err error)

func (QueryFunc) WriteSQL added in v0.3.2

func (q QueryFunc) WriteSQL(w Writer, d Dialect, start int) (args []any, err error)

type ValuedArgument

type ValuedArgument interface {
	Argument
	Value() (any, error)
}

ValuedArgument represents an argument were its value will be provided by this instance.

type Writer

type Writer interface {
	// Write writes a string.
	Write(s string)
	// WriteNewLine writes a newline if in newline-mode, or nothing if not.
	WriteNewLine()
	// WriteSeparator writes a newline if in newline-mode, or a space if not.
	WriteSeparator()
	// AddSeparator schedules a WriteSeparator to be written on the next Write, except on the first Write call.
	// If toplevel is true, will try to write a newline if enabled, if false will add a space.
	AddSeparator(topLevel bool)
	// StartQuery signals the writer that a new query (or subquery) will start. It resets the "first Write" flag.
	StartQuery()
	// Indent increases indentation by 1 (only in newline-mode).
	Indent()
	// Dedent decreases indentation by 1 (only in newline-mode).
	Dedent()
	// Err returns any errors that were generated in the write process.
	Err() error
}

Writer is the interface used by expressions to output strings.

Jump to

Keyboard shortcuts

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