db

package
v0.0.0-...-a942fbd Latest Latest
Warning

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

Go to latest
Published: Apr 25, 2023 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CombineWithOr

func CombineWithOr(qms []qm.QueryMod) []qm.QueryMod

CombineWithOr receives a slice of query mods and returns a new slice with a single query mod, combining all other query mods into an OR expression.

func ILike

func ILike(val string, path ...string) qm.QueryMod

ILike returns a query mod containing a pre-formatted ILIKE clause. The value provided is applied directly - to perform a wildcard search, enclose the desired search value in `%` as desired before passing it to ILike. The path provided will be joined to construct the full SQL path used, allowing for filtering of values nested across multiple joins if needed.

func InnerJoin

func InnerJoin(baseTable string, baseColumn string, joinTable string, joinColumn string) qm.QueryMod

InnerJoin returns an InnerJoin QueryMod formatted using the provided join tables and columns.

func InnerJoinWithFilter

func InnerJoinWithFilter(baseTable string, baseColumn string, joinTable string, joinColumn string, filterColumn string, filterValue interface{}, optFilterTable ...string) qm.QueryMod

InnerJoinWithFilter returns an InnerJoin QueryMod formatted using the provided join tables and columns including an additional filter condition. Omitting the optional filter table will use the provided join table as a base for the filter.

func LeftOuterJoin

func LeftOuterJoin(baseTable string, baseColumn string, joinTable string, joinColumn string) qm.QueryMod

LeftOuterJoin returns an LeftOuterJoin QueryMod formatted using the provided join tables and columns.

func LeftOuterJoinWithFilter

func LeftOuterJoinWithFilter(baseTable string, baseColumn string, joinTable string, joinColumn string, filterColumn string, filterValue interface{}, optFilterTable ...string) qm.QueryMod

LeftOuterJoinWithFilter returns an LeftOuterJoin QueryMod formatted using the provided join tables and columns including an additional filter condition. Omitting the optional filter table will use the provided join table as a base for the filter.

func NullFloat32FromFloat64Ptr

func NullFloat32FromFloat64Ptr(f *float64) null.Float32

func NullIntFromInt64Ptr

func NullIntFromInt64Ptr(i *int64) null.Int

func OrderBy

func OrderBy(orderDir types.OrderDir, path ...string) qm.QueryMod

func OrderByLower

func OrderByLower(orderDir types.OrderDir, path ...string) qm.QueryMod

func OrderByLowerWithNulls

func OrderByLowerWithNulls(orderDir types.OrderDir, orderByNulls OrderByNulls, path ...string) qm.QueryMod

func OrderByWithNulls

func OrderByWithNulls(orderDir types.OrderDir, orderByNulls OrderByNulls, path ...string) qm.QueryMod

func SearchStringToTSQuery

func SearchStringToTSQuery(s *string) string

SearchStringToTSQuery returns a TSQuery string from user input. The resulting query will match if every word matches a beginning of a word in the row. This function will trim all leading and trailing as well as consecutive whitespaces and remove all single quotes before transforming the input into TSQuery syntax. If no input was given (nil or empty string) or the value only contains invalid characters, an empty string will be returned.

func WhereJSON

func WhereJSON(table string, column string, filter interface{}) qm.QueryMod

WhereJSON constructs a QueryMod for querying a JSONB column.

The filter interface provided is inspected using reflection, all fields with a (non-empty) `json` tag will be added to the query and combined using `AND` - fields tagged with `json:"-"` will be ignored as well. Alternatively, a string can be provided, performing a string comparison with the database value (the stored JSON value does not necessarily have to be a string, but could be an integer or similar). The `json` tag's (first) value will be used as the "key" for the query, allowing for field renaming or different capitalizations.

At the moment, the root level `filter` value must either be a struct or a string. WhereJSON will panic should it encounter a type it cannot process or the filter provided results in an empty QueryMod - this allows for easier call chaining at the expense of panics in case of incorrect filters being passed.

WhereJSON should support all basic types as well as pointers and array/slices of those out of the box, given the Postgres driver can handle their serialization. nil pointers are skipped automatically. At the moment, struct fields are only supported for composition purposes: if a struct is encountered, WhereJSON recursively traverses it (up to 10 levels deep) and adds all eligible fields to the top level query. Should an array or slice be encountered, their values will be added using the `<@` JSONB operator, checking whether all entries existx at the top level within the JSON column. At the time of writing, no support for special database/HTTP types such as the `null` or `strfmt` packages exists - use their respective base types instead.

Whilst WhereJSON was designed to be used with Postgres' JSONB column type, the current implementation also supports the JSON type as long as the filter struct does not contain any arrays or slices. Note that this compatibility might change at some point in the future, so it is advised to use the JSONB data type unless your requirements do not allow for it.

Example
package main

import (
	"fmt"

	"github.com/trino-network/pay-srv/internal/models"
	"github.com/trino-network/pay-srv/internal/util/db"
	"github.com/volatiletech/sqlboiler/v4/queries"
	"github.com/volatiletech/sqlboiler/v4/queries/qm"
)

type PublicName struct {
	First string `json:"firstName"`
}

type Name struct {
	PublicName
	MiddleName string `json:"-"`
	Lastname   string `json:"lastName"`
}

type UserFilter struct {
	Name
	Country string `json:"country"`
	City    string
	Scopes  []string `json:"scopes"`
	Age     *int     `json:"age"`
	Height  *float32 `json:"height"`
}

func main() {
	age := 42
	filter := UserFilter{
		Name: Name{
			PublicName: PublicName{
				First: "Max",
			},
			MiddleName: "Gustav",
			Lastname:   "Muster",
		},
		Country: "Austria",
		City:    "Vienna",
		Scopes:  []string{"app", "user_info"},
		Age:     &age,
	}

	q := models.NewQuery(
		qm.Select("*"),
		qm.From("users"),
		db.WhereJSON("users", "profile", filter),
	)

	sql, args := queries.BuildQuery(q)

	fmt.Println(sql)
	fmt.Print("[")
	for i := range args {
		if i < len(args)-1 {
			fmt.Printf("%v, ", args[i])
		} else {
			fmt.Printf("%v", args[i])
		}
	}
	fmt.Println("]")

}
Output:

SELECT * FROM "users" WHERE (users.profile->>'firstName' = $1 AND users.profile->>'lastName' = $2 AND users.profile->>'country' = $3 AND users.profile->'scopes' <@ to_jsonb($4::text[]) AND users.profile->>'age' = $5);
[Max, Muster, Austria, &[app user_info], 42]

func WithConfiguredTransaction

func WithConfiguredTransaction(ctx context.Context, db *sql.DB, options *sql.TxOptions, fn TxFn) error

func WithTransaction

func WithTransaction(ctx context.Context, db *sql.DB, fn TxFn) error

Types

type OrderByNulls

type OrderByNulls string
const (
	OrderByNullsFirst OrderByNulls = "FIRST"
	OrderByNullsLast  OrderByNulls = "LAST"
)

type QueryMods

type QueryMods []qm.QueryMod

QueryMods represents a slice of query mods, implementing the `queries.Applicator` interface to allow for usage with eager loading methods of models. Unfortunately, sqlboiler does not import the (identical) type used by the library, so we have to declare and "implemented" it ourselves...

func (QueryMods) Apply

func (m QueryMods) Apply(q *queries.Query)

Apply applies the query mods to the query provided

type TxFn

type TxFn func(boil.ContextExecutor) error

Jump to

Keyboard shortcuts

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