juice

package module
v1.4.15 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2024 License: Apache-2.0 Imports: 32 Imported by: 0

README

Juice SQL Mapper Framework For Golang

Go Doc Release Go Report Card License

Juice is a SQL mapper framework for Golang, inspired by MyBatis. It is simple, lightweight, and easy to use and extend. This document provides a brief introduction to Juice and its usage.

Installation

To install Juice, use the following command:

go get github.com/eatmoreapple/juice

Example

touch config.xml

add the following content to config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//juice.org//DTD Config 1.0//EN"
        "https://raw.githubusercontent.com/eatmoreapple/juice/main/config.dtd">

<configuration>
    <environments default="prod">
        <environment id="prod">
            <dataSource>root:qwe123@tcp(localhost:3306)/database</dataSource>
            <driver>mysql</driver>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mappers.xml"/>
    </mappers>
</configuration>
touch mappers.xml

add the following content to mappers.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//juice.org//DTD Config 1.0//EN"
        "https://raw.githubusercontent.com/eatmoreapple/juice/main/mapper.dtd">

<mapper namespace="main.Repository">
    <select id="HelloWorld">
        <if test="1 == 1">  <!-- always be true -->
            select "hello world"
        </if>
    </select>
</mapper>
touch main.go

add the following content to main.go

package main

import (
	"context"
	"fmt"
	"github.com/eatmoreapple/juice"
	_ "github.com/go-sql-driver/mysql"
)

type Repository interface {
	HelloWorld(ctx context.Context) (string, error)
}

type RepositoryImpl struct{}

func (r RepositoryImpl) HelloWorld(ctx context.Context) (string, error) {
	manager := juice.ManagerFromContext(ctx)
	var iface Repository = r
	executor := juice.NewGenericManager[string](manager).Object(iface.HelloWorld)
	return executor.QueryContext(ctx, nil)
}

func main() {
	cfg, err := juice.NewXMLConfiguration("config.xml")
	if err != nil {
		panic(err)
	}
	engine, err := juice.DefaultEngine(cfg)
	if err != nil {
		panic(err)
	}
	ctx := juice.ContextWithManager(context.Background(), engine)
	repo := RepositoryImpl{}
	result, err := repo.HelloWorld(ctx)
	fmt.Println(result, err) // hello world <nil>
}
go run main.go

API Documentation

Read the document

License

Juice is licensed under the Apache License, Version 2.0. See LICENSE for the full license text.

Support Me

If you like my work, please consider supporting me by buying me a coffee.

Buy Me A Coffee

Documentation

Overview

Package juice provides a set of utilities for mapping database query results to Go data structures.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrEmptyQuery is an error that is returned when the query is empty.
	ErrEmptyQuery = errors.New("empty query")

	// ErrResultMapNotSet is an error that is returned when the result map is not set.
	ErrResultMapNotSet = errors.New("resultMap not set")

	// ErrSqlNodeNotFound is an error that is returned when the sql node is not found.
	// nolint:unused
	ErrSqlNodeNotFound = errors.New("sql node not found")

	// ErrNilDestination is an error that is returned when the destination is nil.
	ErrNilDestination = errors.New("destination can not be nil")

	// ErrNilRows is an error that is returned when the rows is nil.
	ErrNilRows = errors.New("rows can not be nil")

	// ErrPointerRequired is an error that is returned when the destination is not a pointer.
	ErrPointerRequired = errors.New("destination must be a pointer")
)
View Source
var CacheKeyFunc cacheKeyFunc = func(stmt *Statement, query string, args []any) (string, error) {

	writer := md5.New()
	writer.Write([]byte(stmt.ID() + query))
	if len(args) > 0 {
		item, err := json.Marshal(args)
		if err != nil {
			return "", err
		}
		writer.Write(item)
	}
	return hex.EncodeToString(writer.Sum(nil)), nil
}

CacheKeyFunc is the function which is used to generate the scopeCache key. default is the md5 of the query and args. reset the CacheKeyFunc variable to change the default behavior.

View Source
var ErrNoSession = errors.New("no session found in context")

ErrNoSession is the error that no session found in context.

View Source
var ErrTooManyRows = errors.New("juice: too many rows in result set")

ErrTooManyRows is returned when the result set has too many rows but excepted only one row.

Functions

func Bind

func Bind[T any](rows *sql.Rows) (result T, err error)

Bind sql.Rows to given entity with default mapper

func BindWithResultMap

func BindWithResultMap[T any](rows *sql.Rows, resultMap ResultMap) (result T, err error)

BindWithResultMap bind sql.Rows to given entity with given ResultMap bind cover sql.Rows to given entity dest can be a pointer to a struct, a pointer to a slice of struct, or a pointer to a slice of any type. rows won't be closed when the function returns.

func ContextWithManager

func ContextWithManager(ctx context.Context, manager Manager) context.Context

ContextWithManager returns a new context with the given Manager.

func CtxWithParam added in v1.3.6

func CtxWithParam(ctx context.Context, param Param) context.Context

CtxWithParam returns a new context with the parameter.

func HasTxManager added in v1.3.5

func HasTxManager(ctx context.Context) bool

HasTxManager returns true if the context has a TxManager.

func IsTxManager added in v1.3.5

func IsTxManager(manager Manager) bool

IsTxManager returns true if the manager is a TxManager.

func MustRegisterEvalFunc

func MustRegisterEvalFunc(name string, v any)

MustRegisterEvalFunc registers a function for eval. If an error occurs, it will panic.

func RegisterEnvValueProvider

func RegisterEnvValueProvider(name string, provider EnvValueProvider)

RegisterEnvValueProvider registers an environment value provider. The key is a name of the provider. The value is a provider. It allows to override the default provider.

func RegisterEvalFunc

func RegisterEvalFunc(name string, v any) error

RegisterEvalFunc registers a function for eval. The function must be a function with one return value. And Allowed to overwrite the built-in function.

func SessionWithContext

func SessionWithContext(ctx context.Context, sess Session) context.Context

SessionWithContext returns a new context with the session.

Types

type Action

type Action string

Action defines a sql action.

const (
	// Select is an action for query
	Select Action = "select"

	// Insert is an action for insert
	Insert Action = "insert"

	// Update is an action for update
	Update Action = "update"

	// Delete is an action for delete
	Delete Action = "delete"
)

func (Action) String

func (a Action) String() string

type AdapterExecutorFunc added in v1.4.9

type AdapterExecutorFunc func(Executor) Executor

AdapterExecutorFunc is a function type that implements the ExecutorAdapter interface.

func (AdapterExecutorFunc) AdapterExecutor added in v1.4.9

func (f AdapterExecutorFunc) AdapterExecutor(e Executor) Executor

AdapterExecutor implements the ExecutorAdapter interface.

type BinderRouter added in v1.4.12

type BinderRouter map[string]any

BinderRouter is a map that associates a string key to any value.

type CacheMiddleware added in v1.3.6

type CacheMiddleware[T any] struct {
	// contains filtered or unexported fields
}

CacheMiddleware is a middleware that caches the result of the sql query.

func (*CacheMiddleware[T]) ExecContext added in v1.3.6

func (c *CacheMiddleware[T]) ExecContext(stmt *Statement, next ExecHandler) ExecHandler

ExecContext implements Middleware.

func (*CacheMiddleware[T]) QueryContext added in v1.3.6

func (c *CacheMiddleware[T]) QueryContext(stmt *Statement, next GenericQueryHandler[T]) GenericQueryHandler[T]

QueryContext implements Middleware.

type ChooseNode

type ChooseNode struct {
	WhenNodes     []Node
	OtherwiseNode Node
}

ChooseNode is a node of choose. ChooseNode can have multiple when nodes and one otherwise node. WhenNode is executed when test is true. OtherwiseNode is executed when all when nodes are false.

func (ChooseNode) Accept

func (c ChooseNode) Accept(translator driver.Translator, p Parameter) (query string, args []any, err error)

Accept accepts parameters and returns query and arguments.

type ColumnDestination added in v1.1.3

type ColumnDestination interface {
	// Destination returns the destination for the given reflect value and column.
	Destination(rv reflect.Value, column []string) ([]any, error)
}

ColumnDestination is a column destination which can be used to scan a row.

type ConditionNode

type ConditionNode struct {
	Nodes NodeGroup
	// contains filtered or unexported fields
}

func (*ConditionNode) Accept

func (c *ConditionNode) Accept(translator driver.Translator, p Parameter) (query string, args []any, err error)

Accept accepts parameters and returns query and arguments. Accept implements Node interface.

func (*ConditionNode) Match

func (c *ConditionNode) Match(p Parameter) (bool, error)

Match returns true if test is matched.

func (*ConditionNode) Parse

func (c *ConditionNode) Parse(test string) (err error)

Parse with given expression.

type Configuration

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

Configuration is a configuration of juice.

func NewXMLConfiguration

func NewXMLConfiguration(filename string) (*Configuration, error)

func NewXMLConfigurationWithFS

func NewXMLConfigurationWithFS(fs fs.FS, filename string) (*Configuration, error)

NewXMLConfigurationWithFS creates a new Configuration from an XML file.

func (Configuration) Environments

func (c Configuration) Environments() Environments

Environments returns the environments.

func (Configuration) Mappers

func (c Configuration) Mappers() *Mappers

Mappers returns the mappers.

func (Configuration) Settings

func (c Configuration) Settings() Settings

Settings returns the settings.

type ConfigurationParser

type ConfigurationParser interface {
	// Parse parses the configuration from the reader.
	Parse(reader io.Reader) (*Configuration, error)
}

ConfigurationParser is the interface for parsing configuration.

type DebugMiddleware

type DebugMiddleware struct{}

DebugMiddleware is a middleware that prints the sql statement and the execution time.

func (*DebugMiddleware) ExecContext

func (m *DebugMiddleware) ExecContext(stmt *Statement, next ExecHandler) ExecHandler

ExecContext implements Middleware. ExecContext will print the sql statement and the execution time.

func (*DebugMiddleware) QueryContext

func (m *DebugMiddleware) QueryContext(stmt *Statement, next QueryHandler) QueryHandler

QueryContext implements Middleware. QueryContext will print the sql statement and the execution time.

type Engine

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

Engine is the implementation of Manager interface and the core of juice.

func DefaultEngine

func DefaultEngine(configuration *Configuration) (*Engine, error)

DefaultEngine is the default engine It adds an interceptor to log the statements

func NewEngine

func NewEngine(configuration *Configuration) (*Engine, error)

NewEngine creates a new Engine

func (*Engine) CacheTx added in v1.3.2

func (e *Engine) CacheTx() TxCacheManager

CacheTx returns a TxCacheManager.

func (*Engine) Close added in v1.3.1

func (e *Engine) Close() error

Close closes the database connection if it is not nil.

func (*Engine) ContextCacheTx added in v1.3.2

func (e *Engine) ContextCacheTx(ctx context.Context, opt *sql.TxOptions) TxCacheManager

ContextCacheTx returns a TxCacheManager with the given context.

func (*Engine) ContextTx

func (e *Engine) ContextTx(ctx context.Context, opt *sql.TxOptions) TxManager

ContextTx returns a TxManager with the given context

func (*Engine) DB

func (e *Engine) DB() *sql.DB

DB returns the database connection of the engine

func (*Engine) Driver

func (e *Engine) Driver() driver.Driver

Driver returns the driver of the engine

func (*Engine) GetConfiguration

func (e *Engine) GetConfiguration() *Configuration

GetConfiguration returns the configuration of the engine

func (*Engine) Object

func (e *Engine) Object(v any) Executor

Object implements the Manager interface

func (*Engine) SetConfiguration

func (e *Engine) SetConfiguration(cfg *Configuration)

SetConfiguration sets the configuration of the engine

func (*Engine) SetLocker added in v1.3.3

func (e *Engine) SetLocker(locker RWLocker)

SetLocker sets the locker of the engine it is not goroutine safe, so it should be called before the engine is used

func (*Engine) Tx

func (e *Engine) Tx() TxManager

Tx returns a TxManager

func (*Engine) Use

func (e *Engine) Use(middleware Middleware)

Use adds a middleware to the engine

type EnvValueProvider

type EnvValueProvider interface {
	Get(key string) (string, error)
}

EnvValueProvider defines a environment value provider.

func GetEnvValueProvider

func GetEnvValueProvider(key string) EnvValueProvider

GetEnvValueProvider returns a environment value provider.

type EnvValueProviderFunc

type EnvValueProviderFunc func(key string) (string, error)

EnvValueProviderFunc is a function type of environment value provider.

func (EnvValueProviderFunc) Get

func (f EnvValueProviderFunc) Get(key string) (string, error)

Get is a function type of environment value provider.

type Environment

type Environment struct {
	// DataSource is a string in a driver-specific format.
	DataSource string

	// Driver is a driver for
	Driver string

	// MaxIdleConnNum is a maximum number of idle connections.
	MaxIdleConnNum int

	// MaxOpenConnNum is a maximum number of open connections.
	MaxOpenConnNum int

	// MaxConnLifetime is a maximum lifetime of a connection.
	MaxConnLifetime int

	// MaxIdleConnLifetime is a maximum lifetime of an idle connection.
	MaxIdleConnLifetime int
	// contains filtered or unexported fields
}

Environment defines a environment. It contains a database connection configuration.

func (*Environment) Attr

func (e *Environment) Attr(key string) string

Attr returns a value of the attribute.

func (*Environment) Connect

func (e *Environment) Connect(driver driver.Driver) (*sql.DB, error)

Connect returns a database connection.

func (*Environment) ID

func (e *Environment) ID() string

ID returns a identifier of the environment.

type Environments

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

Environments is a collection of environments.

func (*Environments) Attr added in v1.3.7

func (e *Environments) Attr(key string) string

Attr returns a value of the attribute.

func (*Environments) DefaultEnv

func (e *Environments) DefaultEnv() (*Environment, error)

DefaultEnv returns the default environment.

func (*Environments) Use

func (e *Environments) Use(id string) (*Environment, error)

Use returns the environment specified by the identifier.

type EvalValue added in v1.3.8

type EvalValue = reflect.Value

EvalValue is an alias of reflect.Value. for semantic.

func Eval

func Eval(expr string, params Parameter) (EvalValue, error)

Eval is a shortcut of DefaultEvaluator.Compiler(expr).Execute(params).

type ExecHandler

type ExecHandler func(ctx context.Context, query string, args ...any) (sql.Result, error)

ExecHandler defines the handler of the exec.

type Executor

type Executor interface {
	// QueryContext executes a query that returns rows, typically a SELECT.
	// The param are the placeholder collection for this query.
	QueryContext(ctx context.Context, param Param) (*sql.Rows, error)

	// ExecContext executes a query without returning any rows.
	// The param are the placeholder collection for this query.
	ExecContext(ctx context.Context, param Param) (sql.Result, error)

	// Statement returns the statement of the current executor.
	Statement() *Statement

	// Session returns the session of the current executor.
	Session() Session
}

Executor is an executor of SQL.

type ExecutorAdapter added in v1.4.9

type ExecutorAdapter interface {
	// AdapterExecutor injects the executor and returns the new executor.
	AdapterExecutor(Executor) Executor
}

ExecutorAdapter is an interface for injecting the executor.

func NewParamCtxExecutorAdapter added in v1.4.9

func NewParamCtxExecutorAdapter() ExecutorAdapter

NewParamCtxExecutorAdapter returns a new ParamCtxInjectorExecutor.

func NewSessionCtxInjectorExecutorAdapter added in v1.4.9

func NewSessionCtxInjectorExecutorAdapter() ExecutorAdapter

NewSessionCtxInjectorExecutorAdapter returns a new SessionCtxInjectorExecutor.

type ExecutorAdapterGroup added in v1.4.9

type ExecutorAdapterGroup []ExecutorAdapter

ExecutorAdapterGroup is a group of executor injectors. It implements the ExecutorAdapter interface.

func (ExecutorAdapterGroup) AdapterExecutor added in v1.4.9

func (eg ExecutorAdapterGroup) AdapterExecutor(e Executor) Executor

AdapterExecutor implements the ExecutorAdapter interface. It wrapped the executor by the order of the group.

type ExprCompiler added in v1.4.9

type ExprCompiler interface {
	// Compile compiles the expression and returns the expression.
	Compile(expr string) (Expression, error)
}

ExprCompiler is an evaluator of the expression.

var (
	// DefaultExprCompiler is the default evaluator.
	// Reset it to change the default behavior.
	DefaultExprCompiler ExprCompiler = &goExprCompiler{pretreatment: exprPretreatmentChain}
)

type ExprPretreatment added in v1.4.2

type ExprPretreatment interface {
	PretreatmentExpr(expr string) (string, error)
}

ExprPretreatment is an expression pretreatment. It is used to pretreatment the expression before parsing.

type ExprPretreatmentChain added in v1.4.2

type ExprPretreatmentChain []ExprPretreatment

ExprPretreatmentChain is an expression pretreatment chain.

func (ExprPretreatmentChain) PretreatmentExpr added in v1.4.2

func (e ExprPretreatmentChain) PretreatmentExpr(expr string) (string, error)

PretreatmentExpr implements the ExprPretreatment interface.

type Expression added in v1.3.8

type Expression interface {
	// Execute evaluates the expression and returns the value.
	Execute(params Parameter) (EvalValue, error)
}

Expression is an expression which can be evaluated to a value.

type ForeachNode

type ForeachNode struct {
	Collection string
	Nodes      []Node
	Item       string
	Index      string
	Open       string
	Close      string
	Separator  string
}

ForeachNode is a node of foreach.

func (ForeachNode) Accept

func (f ForeachNode) Accept(translator driver.Translator, p Parameter) (query string, args []any, err error)

Accept accepts parameters and returns query and arguments.

type GenericExecutor

type GenericExecutor[T any] interface {
	// QueryContext executes the query and returns the direct result.
	// The args are for any placeholder parameters in the query.
	QueryContext(ctx context.Context, param Param) (T, error)

	// ExecContext executes a query without returning any rows.
	// The args are for any placeholder parameters in the query.
	ExecContext(ctx context.Context, param Param) (sql.Result, error)

	// Statement returns the statement of the current executor.
	Statement() *Statement

	// Session returns the session of the current executor.
	Session() Session

	// Use adds a middleware to the current executor.
	// The difference between Engine.Use and Executor.Use is only works for the current executor.
	Use(middlewares ...GenericMiddleware[T])
}

GenericExecutor is a generic executor.

type GenericManager

type GenericManager[T any] interface {
	Object(v any) GenericExecutor[T]
}

GenericManager is an interface for managing database operations.

func NewGenericManager

func NewGenericManager[T any](manager Manager) GenericManager[T]

NewGenericManager returns a new GenericManager.

type GenericMiddleware added in v1.3.6

type GenericMiddleware[T any] interface {
	// QueryContext wraps the GenericQueryHandler.
	// The GenericQueryHandler is a function that accepts a context.Context, a query string and a slice of arguments.
	QueryContext(stmt *Statement, next GenericQueryHandler[T]) GenericQueryHandler[T]

	// ExecContext wraps the ExecHandler.
	// The ExecHandler is a function that accepts a context.Context, a query string and a slice of arguments.
	ExecContext(stmt *Statement, next ExecHandler) ExecHandler
}

GenericMiddleware defines the middleware interface for the generic execution.

type GenericMiddlewareGroup added in v1.3.6

type GenericMiddlewareGroup[T any] []GenericMiddleware[T]

GenericMiddlewareGroup is a group of GenericMiddleware. It implements the GenericMiddleware interface.

func (GenericMiddlewareGroup[T]) ExecContext added in v1.3.6

func (m GenericMiddlewareGroup[T]) ExecContext(stmt *Statement, next ExecHandler) ExecHandler

ExecContext implements GenericMiddleware.

func (GenericMiddlewareGroup[T]) QueryContext added in v1.3.6

func (m GenericMiddlewareGroup[T]) QueryContext(stmt *Statement, next GenericQueryHandler[T]) GenericQueryHandler[T]

QueryContext implements GenericMiddleware.

type GenericQueryHandler added in v1.3.6

type GenericQueryHandler[T any] func(ctx context.Context, query string, args ...any) (T, error)

GenericQueryHandler defines the handler of the generic query.

type H

type H map[string]any

H is a shortcut for map[string]any

func (H) AsParam added in v1.2.7

func (h H) AsParam() Parameter

AsParam converts the H to a Parameter.

type IfNode

type IfNode = ConditionNode

IfNode is a node of if.

type IncludeNode

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

IncludeNode is a node of include. It includes another SQL.

func (*IncludeNode) Accept

func (i *IncludeNode) Accept(translator driver.Translator, p Parameter) (query string, args []any, err error)

Accept accepts parameters and returns query and arguments.

type Manager

type Manager interface {
	Object(v any) Executor
}

Manager is an interface for managing database operations.

func ManagerFromContext

func ManagerFromContext(ctx context.Context) Manager

ManagerFromContext returns the Manager from the context.

type Mapper

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

Mapper defines a set of statements.

func (*Mapper) Attribute

func (m *Mapper) Attribute(key string) string

Attribute returns the attribute value by key.

func (*Mapper) Configuration

func (m *Mapper) Configuration() *Configuration

func (*Mapper) Engine added in v1.3.4

func (m *Mapper) Engine() *Engine

func (*Mapper) GetResultMapByID

func (m *Mapper) GetResultMapByID(id string) (ResultMap, error)

func (*Mapper) GetSQLNodeByID

func (m *Mapper) GetSQLNodeByID(id string) (Node, error)

func (*Mapper) Mappers

func (m *Mapper) Mappers() *Mappers

Mappers is an getter of mappers.

func (*Mapper) Namespace

func (m *Mapper) Namespace() string

Namespace returns the namespace of the mapper.

func (*Mapper) Prefix added in v1.1.9

func (m *Mapper) Prefix() string

Prefix returns the prefix of the mapper.

type Mappers

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

Mappers is a map of mappers.

func (*Mappers) Attribute added in v1.1.9

func (m *Mappers) Attribute(key string) string

Attribute returns an attribute from the Mappers attributes.

func (*Mappers) Configuration

func (m *Mappers) Configuration() *Configuration

Configuration represents a configuration of juice.

func (*Mappers) GetMapperByNamespace added in v1.4.6

func (m *Mappers) GetMapperByNamespace(namespace string) (*Mapper, bool)

func (*Mappers) GetStatement

func (m *Mappers) GetStatement(v any) (*Statement, error)

GetStatement try to one the statement from the Mappers with the given interface

func (*Mappers) GetStatementByID

func (m *Mappers) GetStatementByID(id string) (*Statement, error)

GetStatementByID returns a statement by id. If the statement is not found, an error is returned.

func (*Mappers) Prefix added in v1.1.9

func (m *Mappers) Prefix() string

Prefix returns the prefix of the Mappers.

type Middleware

type Middleware interface {
	// QueryContext wraps the QueryHandler.
	QueryContext(stmt *Statement, next QueryHandler) QueryHandler
	// ExecContext wraps the ExecHandler.
	ExecContext(stmt *Statement, next ExecHandler) ExecHandler
}

Middleware is a wrapper of QueryHandler and ExecHandler.

type MiddlewareGroup

type MiddlewareGroup []Middleware

MiddlewareGroup is a group of Middleware.

func (MiddlewareGroup) ExecContext

func (m MiddlewareGroup) ExecContext(stmt *Statement, next ExecHandler) ExecHandler

ExecContext implements Middleware. Call ExecContext will call all the ExecContext of the middlewares in the group.

func (MiddlewareGroup) QueryContext

func (m MiddlewareGroup) QueryContext(stmt *Statement, next QueryHandler) QueryHandler

QueryContext implements Middleware. Call QueryContext will call all the QueryContext of the middlewares in the group.

type Node

type Node interface {
	// Accept accepts parameters and returns query and arguments.
	Accept(translator driver.Translator, p Parameter) (query string, args []any, err error)
}

Node is a node of SQL.

func NewTextNode added in v1.2.9

func NewTextNode(str string) (Node, error)

type NodeGroup added in v1.4.9

type NodeGroup []Node

NodeGroup wraps multiple nodes.

func (NodeGroup) Accept added in v1.4.9

func (g NodeGroup) Accept(translator driver.Translator, p Parameter) (query string, args []any, err error)

Accept accepts parameters and returns query and arguments.

type OsEnvValueProvider

type OsEnvValueProvider struct{}

OsEnvValueProvider is a environment value provider that uses os.Getenv.

func (OsEnvValueProvider) Get

func (p OsEnvValueProvider) Get(key string) (string, error)

Get returns a value of the environment variable. It uses os.Getenv.

type OtherwiseNode

type OtherwiseNode struct {
	Nodes NodeGroup
}

OtherwiseNode is a node of otherwise. OtherwiseNode like else node, but it can not be used alone. If all WhenNode is false, the query of OtherwiseNode will be returned.

func (OtherwiseNode) Accept

func (o OtherwiseNode) Accept(translator driver.Translator, p Parameter) (query string, args []any, err error)

Accept accepts parameters and returns query and arguments.

type Param

type Param = any

Param is an alias of any type. It is used to represent the parameter of the statement and without type limitation.

func ParamFromContext added in v1.3.6

func ParamFromContext(ctx context.Context) Param

ParamFromContext returns the parameter from the context.

type ParamCtxInjectorExecutor added in v1.3.9

type ParamCtxInjectorExecutor struct {
	Executor
}

ParamCtxInjectorExecutor is an executor that injects the param into the context. Which ensures that the param can be used in the middleware.

func (*ParamCtxInjectorExecutor) ExecContext added in v1.3.9

func (e *ParamCtxInjectorExecutor) ExecContext(ctx context.Context, param Param) (sql.Result, error)

ExecContext executes a query without returning any rows. The param are the placeholder collection for this query. The context is injected by the execContext.

func (*ParamCtxInjectorExecutor) QueryContext added in v1.3.9

func (e *ParamCtxInjectorExecutor) QueryContext(ctx context.Context, param Param) (*sql.Rows, error)

QueryContext executes a query that returns rows, typically a SELECT. The param are the placeholder collection for this query. The context is injected by the queryContext.

type ParamGroup added in v1.2.7

type ParamGroup []Parameter

ParamGroup is a group of parameters which implements the Parameter interface.

func (ParamGroup) Get added in v1.2.7

func (g ParamGroup) Get(name string) (reflect.Value, bool)

Get implements Parameter.

type Parameter added in v1.2.7

type Parameter interface {
	// Get returns the value of the named parameter with the type of reflect.Value.
	Get(name string) (reflect.Value, bool)
}

Parameter is the interface that wraps the Get method. Get returns the value of the named parameter.

func NewParameter added in v1.2.7

func NewParameter(v Param) Parameter

NewParameter creates a new parameter with the given value.

type QueryHandler

type QueryHandler func(ctx context.Context, query string, args ...any) (*sql.Rows, error)

QueryHandler defines the handler of the query.

type RWLocker added in v1.3.3

type RWLocker interface {
	RLock()
	RUnlock()
	Lock()
	Unlock()
}

RWLocker is a interface that can be used to lock、unlock and read lock、read unlock.

type ResultBinder added in v1.4.12

type ResultBinder interface {
	BindTo(v reflect.Value) (BinderRouter, error)
}

ResultBinder is an interface that defines a single method BindTo. This method takes a reflect.Value and returns a BinderRouter and an error.

type ResultBinderGroup added in v1.4.12

type ResultBinderGroup []ResultBinder

ResultBinderGroup is a slice of ResultBinders.

func (ResultBinderGroup) BindTo added in v1.4.12

BindTo method for a group of ResultBinders. It iterates over each binder in the group, calls its BindTo method, and merges the results into a single BinderRouter. If a key is found in more than one binder, it returns an error.

type ResultMap

type ResultMap interface {
	// ResultTo maps the data from the SQL row to the provided reflect.Value.
	ResultTo(rv reflect.Value, row *sql.Rows) error
}

ResultMap is an interface that defines a method for mapping database query results to Go data structures.

type RowResultMap added in v1.1.1

type RowResultMap struct{}

RowResultMap is a ResultMap that maps a rowDestination to a non-slice type.

func (RowResultMap) ResultTo added in v1.1.1

func (RowResultMap) ResultTo(rv reflect.Value, rows *sql.Rows) error

ResultTo implements ResultMapper interface. It maps the data from the SQL row to the provided reflect.Value. If more than one row is returned from the query, it returns an ErrTooManyRows error.

type RowsResultMap added in v1.1.1

type RowsResultMap struct{}

RowsResultMap is a ResultMap that maps a rowDestination to a slice type.

func (RowsResultMap) ResultTo added in v1.1.1

func (RowsResultMap) ResultTo(rv reflect.Value, rows *sql.Rows) error

ResultTo implements ResultMapper interface. It maps the data from the SQL row to the provided reflect.Value. It maps each row to a new element in a slice.

type RowsScanner added in v1.1.2

type RowsScanner interface {
	ScanRows(rows *sql.Rows) error
}

RowsScanner scan sql.Rows to dest.

type SQLNode

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

SQLNode is a node of sql. SQLNode defines a SQL query.

func (SQLNode) Accept

func (s SQLNode) Accept(translator driver.Translator, p Parameter) (query string, args []any, err error)

Accept accepts parameters and returns query and arguments.

func (SQLNode) ID

func (s SQLNode) ID() string

ID returns the id of the node.

type SelectFieldAliasNode added in v1.1.4

type SelectFieldAliasNode []*selectFieldAliasItem

SelectFieldAliasNode is a node of select field alias.

func (SelectFieldAliasNode) Accept added in v1.1.4

func (s SelectFieldAliasNode) Accept(_ driver.Translator, _ Parameter) (query string, args []any, err error)

Accept accepts parameters and returns query and arguments.

type Session

type Session interface {
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
}

Session is a wrapper of sql.DB and sql.Tx

func SessionFromContext

func SessionFromContext(ctx context.Context) Session

SessionFromContext returns the session from the context.

type SessionCtxInjectorExecutor added in v1.3.9

type SessionCtxInjectorExecutor struct {
	Executor
}

SessionCtxInjectorExecutor is an executor that injects the session into the context. Which ensures that the session can be used in the middleware.

func (*SessionCtxInjectorExecutor) ExecContext added in v1.3.9

func (e *SessionCtxInjectorExecutor) ExecContext(ctx context.Context, param Param) (sql.Result, error)

ExecContext executes a query without returning any rows. The param are the placeholder collection for this query. The context is injected by the sessionContext.

func (*SessionCtxInjectorExecutor) QueryContext added in v1.3.9

func (e *SessionCtxInjectorExecutor) QueryContext(ctx context.Context, param Param) (*sql.Rows, error)

QueryContext executes a query that returns rows, typically a SELECT. The param are the placeholder collection for this query. The context is injected by the sessionContext.

type SetNode

type SetNode struct {
	Nodes []Node
}

SetNode is a node of set.

func (SetNode) Accept

func (s SetNode) Accept(translator driver.Translator, p Parameter) (query string, args []any, err error)

Accept accepts parameters and returns query and arguments.

type Setting

type Setting struct {
	// The name of the setting.
	Name string `xml:"name,attr"`
	// The value of the setting.
	Value StringValue `xml:"value,attr"`
}

Setting is a setting element.

type Settings

type Settings map[string]StringValue

Settings is a collection of settings.

func (Settings) Get

func (s Settings) Get(name string) StringValue

Get returns the value of the key.

type Statement

type Statement struct {
	Nodes []Node
	// contains filtered or unexported fields
}

Statement defines a sql statement.

func (*Statement) Accept

func (s *Statement) Accept(translator driver.Translator, p Parameter) (query string, args []any, err error)

func (*Statement) Action

func (s *Statement) Action() Action

func (*Statement) Attribute

func (s *Statement) Attribute(key string) string

func (*Statement) Build added in v1.3.2

func (s *Statement) Build(param Param) (query string, args []any, err error)

Build builds the statement with the given parameter.

func (*Statement) Configuration

func (s *Statement) Configuration() *Configuration

Configuration returns the configuration of the statement.

func (*Statement) Engine

func (s *Statement) Engine() *Engine

Engine returns the engine of the statement.

func (*Statement) ExecHandler added in v1.3.2

func (s *Statement) ExecHandler() ExecHandler

ExecHandler returns the ExecHandler of the statement.

func (*Statement) ForRead

func (s *Statement) ForRead() bool

ForRead returns true if the statement's Action is Select

func (*Statement) ForWrite

func (s *Statement) ForWrite() bool

ForWrite returns true if the statement's Action is Insert, Update or Delete

func (*Statement) ID

func (s *Statement) ID() string

func (*Statement) IsInsert added in v1.2.9

func (s *Statement) IsInsert() bool

IsInsert returns true if the statement's Action is Insert

func (*Statement) Mapper

func (s *Statement) Mapper() *Mapper

Mapper is an getter of statements.

func (*Statement) Name added in v1.1.9

func (s *Statement) Name() string

Name is a unique key of the whole statement.

func (*Statement) Namespace

func (s *Statement) Namespace() string

func (*Statement) QueryHandler added in v1.3.2

func (s *Statement) QueryHandler() QueryHandler

QueryHandler returns the QueryHandler of the statement.

func (*Statement) ResultMap

func (s *Statement) ResultMap() (ResultMap, error)

ResultMap returns the ResultMap of the statement.

type StringValue

type StringValue string

StringValue is a string value which can be converted to other types.

func (StringValue) Bool

func (s StringValue) Bool() bool

Bool returns true if the value is "true".

func (StringValue) Float64

func (s StringValue) Float64() float64

Float64 returns the value as float64.

func (StringValue) Int64

func (s StringValue) Int64() int64

Int64 returns the value as int64.

func (StringValue) String

func (s StringValue) String() string

String returns the value as string.

func (StringValue) Uint64 added in v1.3.9

func (s StringValue) Uint64() uint64

Uint64 returns the value as uint64.

func (StringValue) Unmarshaler added in v1.3.9

func (s StringValue) Unmarshaler(marshaller encoding.TextUnmarshaler) error

Unmarshaler unmarshals the value to given marshaller.

type SyntaxError

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

SyntaxError represents a syntax error. The error occurs when parsing the expression.

func (*SyntaxError) Error

func (s *SyntaxError) Error() string

Error returns the error message.

func (*SyntaxError) Unwrap added in v1.2.7

func (s *SyntaxError) Unwrap() error

Unwrap returns the underlying error.

type TextNode

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

TextNode is a node of text. What is the difference between TextNode and pureTextNode? TextNode is used to replace parameters with placeholders. pureTextNode is used to avoid unnecessary parameter replacement.

func (*TextNode) Accept

func (c *TextNode) Accept(translator driver.Translator, p Parameter) (query string, args []any, err error)

Accept accepts parameters and returns query and arguments. Accept implements Node interface.

type TimeoutMiddleware

type TimeoutMiddleware struct{}

TimeoutMiddleware is a middleware that sets the timeout for the sql statement.

func (TimeoutMiddleware) ExecContext

func (t TimeoutMiddleware) ExecContext(stmt *Statement, next ExecHandler) ExecHandler

ExecContext implements Middleware. ExecContext will set the timeout for the sql statement.

func (TimeoutMiddleware) QueryContext

func (t TimeoutMiddleware) QueryContext(stmt *Statement, next QueryHandler) QueryHandler

QueryContext implements Middleware. QueryContext will set the timeout for the sql statement.

type TrimNode

type TrimNode struct {
	Nodes           []Node
	Prefix          string
	PrefixOverrides []string
	Suffix          string
	SuffixOverrides []string
}

TrimNode is a node of trim.

func (TrimNode) Accept

func (t TrimNode) Accept(translator driver.Translator, p Parameter) (query string, args []any, err error)

Accept accepts parameters and returns query and arguments.

type TxCacheManager added in v1.3.2

type TxCacheManager interface {
	TxManager
	Cache() cache.ScopeCache
}

TxCacheManager defines a transactional scopeCache manager whose scopeCache can be accessed. All queries in the transaction will be cached. scopeCache.Flush() will be called after Commit() or Rollback().

func NewTxCacheManager added in v1.3.2

func NewTxCacheManager(manager TxManager, cache cache.ScopeCache) TxCacheManager

NewTxCacheManager returns a new TxCacheManager.

type TxManager

type TxManager interface {
	Manager
	// Commit commits the transaction.
	Commit() error
	// Rollback rollbacks the transaction.
	// The rollback will be ignored if the tx has been committed.
	Rollback() error
}

TxManager is a transactional mapper executor

type ValuesNode added in v1.1.4

type ValuesNode []*valueItem

ValuesNode is a node of values. only support for insert.

func (ValuesNode) Accept added in v1.1.4

func (v ValuesNode) Accept(translater driver.Translator, param Parameter) (query string, args []any, err error)

Accept accepts parameters and returns query and arguments.

type WhenNode

type WhenNode = ConditionNode

WhenNode is a node of when. WhenNode like if node, but it can not be used alone. While one of WhenNode is true, the query of ChooseNode will be returned.

type WhereNode

type WhereNode struct {
	Nodes []Node
}

WhereNode is a node of where.

func (WhereNode) Accept

func (w WhereNode) Accept(translator driver.Translator, p Parameter) (query string, args []any, err error)

Accept accepts parameters and returns query and arguments.

type XMLParser

type XMLParser struct {
	FS fs.FS
	// contains filtered or unexported fields
}

XMLParser is the parser for XML configuration.

func (*XMLParser) Parse

func (p *XMLParser) Parse(reader io.Reader) (*Configuration, error)

Parse implements ConfigurationParser.

Jump to

Keyboard shortcuts

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