builder

package module
v0.0.0-...-33d5556 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2025 License: MIT Imports: 4 Imported by: 0

README

go-sqlbuilder

Build Status Go Report Card Coverage Status MIT licensed

A lightweight and fluent SQL query builder for Go, designed to make database query construction simple, safe, and maintainable. It supports multiple SQL dialects and provides a rich set of features for building complex queries.

Features

  • Fluent interface for building SQL queries
  • Support for multiple SQL dialects (MySQL, PostgreSQL, SQLite)
  • Comprehensive query building capabilities:
    • SELECT queries with WHERE, ORDER BY, and LIMIT clauses
    • INSERT and REPLACE operations
    • INSERT ... ON DUPLICATE KEY UPDATE for MySQL
    • UPDATE queries with SET and WHERE clauses
    • DELETE operations
    • Raw SQL support
  • Advanced conditions:
    • Complex WHERE clauses with AND/OR combinations
    • IN, NOT IN operators
    • BETWEEN, NOT BETWEEN operators
    • Comparison operators (=, !=, >, <, >=, <=)
  • Parameterized queries for SQL injection prevention
  • Proper identifier escaping based on dialect
  • Last query tracking for debugging
  • Chainable methods for query construction

Installation

go get -u github.com/DropFan/go-sqlbuilder

Usage

Basic Examples
import (
    builder "github.com/DropFan/go-sqlbuilder"
)

// Create a new builder instance
b := builder.New()

// Simple SELECT query
query, err := b.Select("id", "name", "age").
    From("users").
    Where(builder.Eq("status", "active")).
    Build()

// INSERT query
query, err = b.Insert("users", "name", "age").
    Values([]interface{}{"John", 25}).
    Build()

// INSERT ... ON DUPLICATE KEY UPDATE
query, err = b.InsertOrUpdate("users",
    &builder.FieldValue{Name: "name", Value: "John"},
    &builder.FieldValue{Name: "age", Value: 25}).
    Build()

// UPDATE query
query, err = b.Update("users",
    &builder.FieldValue{Name: "age", Value: 26},
    &builder.FieldValue{Name: "status", Value: "inactive"}).
    Where(builder.Eq("id", 1)).
    Build()

// DELETE query
query, err = b.Delete("users").
    Where(builder.Eq("id", 1)).
    Build()
Advanced WHERE Conditions
// Complex WHERE clause with AND/OR conditions
query, err := b.Select("*").
    From("users").
    Where(
        builder.Eq("status", "active"),
        builder.Gt("age", 18),
    ).
    And(
        builder.In("role", "admin", "moderator"),
    ).
    Or(
        builder.Between("last_login", "2023-01-01", "2023-12-31"),
    ).
    Build()

// Using IN operator
query, err = b.Select("*").
    From("users").
    Where(builder.In("role", "admin", "moderator", "editor")).
    Build()

// Using BETWEEN operator
query, err = b.Select("*").
    From("users").
    Where(builder.Between("age", 18, 30)).
    Build()
Using Different Dialects
// MySQL dialect (default)
b.SetDialector(builder.MysqlDialector)
// Output: SELECT `id`, `name` FROM `users` WHERE `age` > ?

// PostgreSQL dialect
b.SetDialector(builder.PostgresDialector)
// Output: SELECT "id", "name" FROM "users" WHERE "age" > $1

// SQLite dialect
b.SetDialector(builder.SQLiteDialector)
// Output: SELECT "id", "name" FROM "users" WHERE "age" > ?
Raw SQL Support
// Using raw SQL when needed
query, err := b.Raw("SELECT * FROM users WHERE id = ?", 1).Build()

TODO

  • Dialect support for MySQL/PostgreSQL/SQLite (escape characters)
  • Dialect-specific placeholder support (MySQL: ?, PostgreSQL: $n)
  • Additional SQL features:
    • GROUP BY and HAVING clauses
    • JOIN operations (INNER, LEFT, RIGHT)
    • Sub-queries
  • Query result scanning utilities
  • Simple ORM-like features
  • Connection pool management
  • Transaction support
  • Schema migration tools

Contributing

Contributions are welcome! Feel free to:

  • Report bugs
  • Suggest new features
  • Submit pull requests
  • Improve documentation

Please ensure your pull request adheres to the following guidelines:

  • Write clear and descriptive commit messages
  • Add tests for new features
  • Update documentation as needed

Contacts

Author: Tiger

Email: DropFan@Gmail.com

Wechat: Hacking4fun

Telegram: DropFan

https://about.me/DropFan

License

MIT

Documentation

Overview

Package builder provides a fluent SQL query builder with support for multiple SQL dialects. It offers a clean and intuitive API for constructing SQL queries programmatically while handling proper escaping and parameter binding based on the target database system.

The package supports multiple SQL dialects including MySQL, PostgreSQL, and SQLite, with appropriate escaping and placeholder styles for each. It provides a type-safe way to build complex SQL queries without string concatenation or manual escaping.

Example usage:

b := builder.New()
query, err := b.Select("id", "name").From("users").Where(builder.Eq("status", "active")).Build()

For more examples, see the builder_test.go file.

Package builder provides a fluent SQL query builder with support for multiple SQL dialects.

Package builder provides a fluent SQL query builder with support for multiple SQL dialects.

Package builder provides a fluent SQL query builder with support for multiple SQL dialects.

Package builder provides a fluent SQL query builder with support for multiple SQL dialects.

Package builder provides a fluent SQL query builder with support for multiple SQL dialects.

Package builder provides a fluent SQL query builder with support for multiple SQL dialects.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrEmptyCondition is returned when attempting to build a condition without
	// providing the necessary field, operator, or values.
	ErrEmptyCondition = errors.New("empty condition")

	// ErrEmptySQLType is returned when attempting to build a query without
	// specifying the SQL operation type (SELECT, INSERT, etc.).
	ErrEmptySQLType = errors.New("empty sql type")

	// ErrListIsNotEmpty is returned when there are accumulated errors during
	// query construction. This typically indicates invalid SQL syntax or
	// incompatible operations.
	ErrListIsNotEmpty = errors.New("there are some errors in SQL, please check your query")
)

Error variables for common SQL builder error conditions. These errors are returned by various methods in the package to indicate specific error conditions during query construction.

Functions

This section is empty.

Types

type Builder

type Builder struct {

	// ErrList collects any errors encountered during query construction
	ErrList []error
	// contains filtered or unexported fields
}

Builder represents a SQL query builder that supports multiple SQL dialects. It provides a fluent interface for constructing SQL queries with proper escaping and parameter binding.

It is recommended to create a new Builder instance using the New() function. For usage examples, please refer to builder_test.go.

func New

func New() *Builder

New creates and initializes a new Builder instance with default MySQL dialect. For usage examples, please refer to builder_test.go.

func (*Builder) And

func (b *Builder) And(conditions ...*Condition) *Builder

And adds one or more conditions to the query using AND logic. If a single condition is provided, it adds "AND condition". If multiple conditions are provided, it adds "AND (condition1 AND condition2 ...)" It returns the Builder instance for method chaining.

func (*Builder) Append

func (b *Builder) Append(s string, args ...interface{}) *Builder

Append adds the provided string and arguments to the end of the current query. It returns the Builder instance for method chaining.

func (*Builder) AppendPre

func (b *Builder) AppendPre(s string, args ...interface{}) *Builder

AppendPre adds the provided string and arguments to the beginning of the current query. It returns the Builder instance for method chaining.

func (*Builder) Between

func (b *Builder) Between(field string, values ...interface{}) *Builder

Between adds a BETWEEN condition to the query for the specified field and range values. It expects exactly two values defining the range (start and end). It returns the Builder instance for method chaining.

Example:

b.Select("*").From("orders").Between("amount", 100, 1000)
// Generates: SELECT * FROM orders WHERE amount BETWEEN ? AND ?

func (*Builder) Build

func (b *Builder) Build(queries ...interface{}) (q *Query, err error)

Build finalizes the query construction and returns a Query object along with any errors. It validates the SQL type and any accumulated errors before creating the final query.

func (*Builder) Clear

func (b *Builder) Clear() *Builder

Clear resets the current query and its arguments to their initial state. It returns the Builder instance for method chaining.

func (*Builder) Count

func (b *Builder) Count(query ...string) *Builder

Count begins a SELECT COUNT query. It can count all rows (COUNT(1)) or specific fields/expressions. It returns the Builder instance for method chaining.

Parameters:

  • query: Optional string(s) to specify what to count (e.g., "DISTINCT column") If not provided, defaults to COUNT(1)

Example:

// Count all rows
b.Count().From("users")
// Generates: SELECT COUNT(1) FROM users

// Count distinct values
b.Count("DISTINCT status").From("orders")
// Generates: SELECT COUNT(DISTINCT status) FROM orders

func (*Builder) Delete

func (b *Builder) Delete(tableName string) *Builder

Delete begins a DELETE query for the specified table. It returns the Builder instance for method chaining.

func (*Builder) Escape

func (b *Builder) Escape(s ...string) string

Escape escapes the provided field names according to the current SQL dialect's rules. It returns the escaped string representation of the fields.

func (*Builder) EscapeChar

func (b *Builder) EscapeChar() string

EscapeChar returns the escape character used by the current SQL dialect for escaping identifiers.

func (*Builder) From

func (b *Builder) From(tables ...string) *Builder

From specifies the tables to select from in a SELECT query. It returns the Builder instance for method chaining.

func (*Builder) FromRaw

func (b *Builder) FromRaw(from string) *Builder

FromRaw specifies a raw FROM clause without any escaping. It returns the Builder instance for method chaining.

func (*Builder) In

func (b *Builder) In(field string, values ...interface{}) *Builder

In adds an IN condition to the query for the specified field and values. It is equivalent to "field IN (value1, value2, ...)" It returns the Builder instance for method chaining.

Example:

b.Select("*").From("users").In("status", "active", "pending")
// Generates: SELECT * FROM users WHERE status IN (?, ?)

In creates an IN condition for the specified field and values. It returns the Builder instance for method chaining.

Parameters:

  • field: The field name to check against
  • values: Variable number of values to include in the IN clause

Example:

b.Select("*").From("users")
  .Where(builder.In("status", "active", "pending"))
// Generates: SELECT * FROM users WHERE `status` IN (?, ?)

func (*Builder) Insert

func (b *Builder) Insert(tableName string, fields ...string) *Builder

Insert begins an INSERT query for the specified table and optional field names. It returns the Builder instance for method chaining.

func (*Builder) InsertOrUpdate

func (b *Builder) InsertOrUpdate(tableName string, fvals ...*FieldValue) *Builder

InsertOrUpdate begins an INSERT ... ON DUPLICATE KEY UPDATE query for MySQL. It takes field-value pairs that will be used for both the INSERT and UPDATE parts. It returns the Builder instance for method chaining.

func (*Builder) Into

func (b *Builder) Into(fields ...string) *Builder

Into specifies the fields for an INSERT or REPLACE query. It returns the Builder instance for method chaining.

func (*Builder) LastQueries

func (b *Builder) LastQueries() []*Query

LastQueries returns all previously built queries in this builder instance.

func (*Builder) LastQuery

func (b *Builder) LastQuery() *Query

LastQuery returns the most recently built query, or nil if no queries have been built.

func (*Builder) Limit

func (b *Builder) Limit(limitOffset ...int) *Builder

Limit adds a LIMIT clause to the query to restrict the number of rows returned. It can be used in two ways: 1. With a single argument to limit the number of rows 2. With two arguments to specify both offset and limit

Parameters:

  • limitOffset: One or two integers:
  • With one argument: The maximum number of rows to return
  • With two arguments: The offset and the maximum number of rows

Example:

// Limit to 10 rows
b.Select("*").From("users").Limit(10)
// Skip 20 rows and return next 10
b.Select("*").From("users").Limit(20, 10)

func (*Builder) NotBetween

func (b *Builder) NotBetween(field string, values ...interface{}) *Builder

NotBetween adds a NOT BETWEEN condition to the query for the specified field and range values. It expects exactly two values defining the range (start and end). It returns the Builder instance for method chaining.

Example:

b.Select("*").From("orders").NotBetween("amount", 0, 100)
// Generates: SELECT * FROM orders WHERE amount NOT BETWEEN ? AND ?

func (*Builder) NotIn

func (b *Builder) NotIn(field string, values ...interface{}) *Builder

NotIn adds a NOT IN condition to the query for the specified field and values. It is equivalent to "field NOT IN (value1, value2, ...)" It returns the Builder instance for method chaining.

Example:

b.Select("*").From("users").NotIn("status", "deleted", "banned")
// Generates: SELECT * FROM users WHERE status NOT IN (?, ?)

func (*Builder) Or

func (b *Builder) Or(conditions ...*Condition) *Builder

Or adds one or more conditions to the query using OR logic. If a single condition is provided, it adds "OR condition". If multiple conditions are provided, it adds "OR (condition1 OR condition2 ...)" It returns the Builder instance for method chaining.

func (*Builder) OrderBy

func (b *Builder) OrderBy(conditions ...*Condition) *Builder

OrderBy specifies the ORDER BY clause with the given conditions. Each condition determines the field and sort direction (ASC/DESC). Multiple conditions can be combined to sort by multiple fields. It returns the Builder instance for method chaining.

Parameters:

  • conditions: One or more Condition objects specifying the sort fields and directions

Example:

b.Select("*").From("users")
  .OrderBy(
    builder.Asc("created_at"),    // Sort by created_at ASC
    builder.Desc("last_login"),   // Then by last_login DESC
  )
// Generates: SELECT * FROM users ORDER BY `created_at` ASC, `last_login` DESC

func (*Builder) Query

func (b *Builder) Query() string

Query returns the current SQL query string being constructed.

func (*Builder) QueryArgs

func (b *Builder) QueryArgs() []interface{}

QueryArgs returns the current list of query arguments that will be used for parameter binding.

func (*Builder) Raw

func (b *Builder) Raw(s string, args ...interface{}) *Builder

Raw sets a raw SQL query string with optional arguments. It returns the Builder instance for method chaining.

func (*Builder) Replace

func (b *Builder) Replace(tableName string, fields ...string) *Builder

Replace begins a REPLACE query for the specified table and optional field names. It returns the Builder instance for method chaining.

func (*Builder) Select

func (b *Builder) Select(fields ...string) *Builder

Select begins a SELECT query with the specified fields. If no fields are provided, it creates an empty SELECT. If "*" is provided as the first field, it selects all columns. It returns the Builder instance for method chaining.

func (*Builder) Set

func (b *Builder) Set(fvals ...*FieldValue) *Builder

Set specifies the field-value pairs to update in an UPDATE query. It returns the Builder instance for method chaining.

func (*Builder) SetDialector

func (b *Builder) SetDialector(d Dialector) *Builder

SetDialector sets the SQL dialect for parameter binding placeholders and identifier escaping. It returns the Builder instance for method chaining.

func (*Builder) Update

func (b *Builder) Update(tableName string, fvals ...*FieldValue) *Builder

Update begins an UPDATE query for the specified table with optional field-value pairs. It returns the Builder instance for method chaining.

func (*Builder) Values

func (b *Builder) Values(valsGroup ...[]interface{}) *Builder

Values adds one or more sets of values to an INSERT or REPLACE query. Each set of values must match the number of fields specified in Into(). It returns the Builder instance for method chaining.

func (*Builder) Where

func (b *Builder) Where(conditions ...*Condition) *Builder

Where begins the WHERE clause of a query with the specified conditions. If no conditions are provided, it adds "WHERE 1". It returns the Builder instance for method chaining.

func (*Builder) WhereRaw

func (b *Builder) WhereRaw(str string, args ...interface{}) *Builder

WhereRaw adds a raw WHERE clause without any escaping or parameter binding. This method is useful when you need to write complex WHERE conditions that cannot be easily expressed using the standard condition builders. It returns the Builder instance for method chaining.

Warning: Be careful when using this method with user-provided input as it may lead to SQL injection vulnerabilities. Use the standard Where method with proper parameter binding when possible.

Parameters:

  • str: The raw WHERE clause string
  • args: Optional arguments for parameter binding

Example:

// Using raw SQL function
b.Select("*").From("posts")
  .WhereRaw("DATE(created_at) = CURDATE()")

// With parameter binding
b.Select("*").From("users")
  .WhereRaw("FIND_IN_SET(?, roles)", "admin")
// Generates: SELECT * FROM users WHERE FIND_IN_SET(?, roles)

type Condition

type Condition struct {
	Field    string        // The name of the database field or column
	Asc      bool          // Sort direction: true for ASC, false for DESC
	AndOr    bool          // Logical operator: true for AND, false for OR
	Operator string        // SQL operator (e.g., =, >, LIKE, IN, etc.)
	Values   []interface{} // The values to compare against the field
}

Condition represents a SQL condition that can be used in WHERE clauses or ORDER BY statements. It supports various SQL operators and can be combined using AND/OR logic.

Conditions can be created using helper functions like And(), Or(), Between(), In(), etc. Multiple conditions can be combined to create complex WHERE clauses with proper operator precedence and grouping.

Example usage:

// Simple condition
cond1 := builder.And("status", "=", "active")

// Multiple conditions combined
cond2 := builder.Or("role", "IN", "admin", "moderator")
b.Select("*").From("users").Where(cond1, cond2)

func And

func And(field string, op string, values ...interface{}) *Condition

And creates a new condition that will be combined with AND logic. It takes a field name, operator, and values to construct the condition.

Parameters:

  • field: The database column or field name
  • op: The SQL operator (e.g., "=", ">", "LIKE", etc.)
  • values: The values to compare against the field

Example:

// Creates: WHERE age >= 18 AND status = 'active'
b.Where(
	builder.And("age", ">=", 18),
	builder.And("status", "=", "active"),
)

func Asc

func Asc(field string) *Condition

Asc creates a new ascending ORDER BY condition for the specified field. It is used to sort results in ascending order.

func Between

func Between(field string, values ...interface{}) *Condition

Between creates a new BETWEEN condition for the specified field. The values parameter should contain exactly two values defining the range.

Parameters:

  • field: The database column or field name
  • values: Exactly two values defining the range (start and end)

Example:

// Creates: WHERE price BETWEEN 10 AND 100
b.Where(builder.Between("price", 10, 100))

func Desc

func Desc(field string) *Condition

Desc creates a new descending ORDER BY condition for the specified field. It is used to sort results in descending order.

func Eq

func Eq(field string, value interface{}) *Condition

Eq creates a new equality condition for the specified field and value.

Parameters:

  • field: The database column or field name
  • value: The value to compare against the field

Example:

// Creates: WHERE status = 'active'
b.Where(builder.Eq("status", "active"))

func Gt

func Gt(field string, value interface{}) *Condition

Gt creates a new greater than condition for the specified field and value.

Parameters:

  • field: The database column or field name
  • value: The value to compare against the field

Example:

// Creates: WHERE age > 18
b.Where(builder.Gt("age", 18))

func Gte

func Gte(field string, value interface{}) *Condition

Gte creates a new greater than or equal to condition for the specified field and value.

Parameters:

  • field: The database column or field name
  • value: The value to compare against the field

Example:

// Creates: WHERE age >= 18
b.Where(builder.Gte("age", 18))

func In

func In(field string, values ...interface{}) *Condition

In creates a new IN condition for the specified field. The values parameter contains the list of values to match against.

Parameters:

  • field: The database column or field name
  • values: One or more values to include in the IN clause

Example:

// Creates: WHERE status IN ('pending', 'processing', 'completed')
b.Where(builder.In("status", "pending", "processing", "completed"))

func Like

func Like(field string, value interface{}) *Condition

Like creates a new LIKE condition for the specified field and value.

Parameters:

  • field: The database column or field name
  • value: The value to compare against the field

Example:

// Creates: WHERE name LIKE '%John%'
b.Where(builder.Like("name", "%John%"))

func Lt

func Lt(field string, value interface{}) *Condition

Lt creates a new less than condition for the specified field and value.

Parameters:

  • field: The database column or field name
  • value: The value to compare against the field

Example:

// Creates: WHERE age < 18
b.Where(builder.Lt("age", 18))

func Lte

func Lte(field string, value interface{}) *Condition

Lte creates a new less than or equal to condition for the specified field and value.

Parameters:

  • field: The database column or field name
  • value: The value to compare against the field

Example:

// Creates: WHERE age <= 18
b.Where(builder.Lte("age", 18))

func NewConditionGroup

func NewConditionGroup(conds ...*Condition) (cg []*Condition)

NewConditionGroup creates a group of conditions that can be used together. It accepts multiple conditions and returns them as a slice.

Warning: Do not mix OrderBy and Where conditions in the same group as they serve different purposes and may lead to unexpected behavior.

func NotBetween

func NotBetween(field string, values ...interface{}) *Condition

NotBetween creates a new NOT BETWEEN condition for the specified field. The values parameter should contain exactly two values defining the range.

Parameters:

  • field: The database column or field name
  • values: Exactly two values defining the range (start and end)

Example:

// Creates: WHERE age NOT BETWEEN 0 AND 18
b.Where(builder.NotBetween("age", 0, 18))

func NotEq

func NotEq(field string, value interface{}) *Condition

NotEq creates a new inequality condition for the specified field and value.

Parameters:

  • field: The database column or field name
  • value: The value to compare against the field

Example:

// Creates: WHERE status != 'active'
b.Where(builder.NotEq("status", "active"))

func NotIn

func NotIn(field string, values ...interface{}) *Condition

NotIn creates a new NOT IN condition for the specified field. The values parameter contains the list of values to exclude.

Parameters:

  • field: The database column or field name
  • values: One or more values to exclude in the NOT IN clause

Example:

// Creates: WHERE status NOT IN ('deleted', 'banned')
b.Where(builder.NotIn("status", "deleted", "banned"))

func NotLike

func NotLike(field string, value interface{}) *Condition

NotLike creates a new NOT LIKE condition for the specified field and value.

Parameters:

  • field: The database column or field name
  • value: The value to compare against the field

Example:

// Creates: WHERE name NOT LIKE '%John%'
b.Where(builder.NotLike("name", "%John%"))

func Or

func Or(field string, op string, values ...interface{}) *Condition

Or creates a new condition that will be combined with OR logic. It takes a field name, operator, and values to construct the condition.

Parameters:

  • field: The database column or field name
  • op: The SQL operator (e.g., "=", ">", "LIKE", etc.)
  • values: The values to compare against the field

Example:

// Creates: WHERE role = 'admin' OR role = 'moderator'
b.Where(
	builder.Or("role", "=", "admin"),
	builder.Or("role", "=", "moderator"),
)

func OrderBy

func OrderBy(conds ...*Condition) (by []*Condition)

OrderBy creates a new slice of ordering conditions. It accepts multiple order conditions and combines them into a single ordering clause.

type Dialector

type Dialector interface {
	// Escape returns the escaped version of the provided identifiers
	// according to the dialect's escaping rules.
	Escape(s ...string) string

	// Placeholder returns the parameter placeholder for the given index.
	// For MySQL it returns "?", for PostgreSQL it returns "$n" where n is the index.
	Placeholder(index int) string

	// GetEscapeChar returns the character used for escaping identifiers
	// in the specific SQL dialect (e.g., backtick for MySQL, double quote for PostgreSQL).
	GetEscapeChar() string
}

Dialector defines the interface for SQL dialect-specific operations. It provides methods for handling placeholder styles (e.g., ? for MySQL, $n for PostgreSQL) and identifier escaping conventions for different SQL databases.

Each database type (MySQL, PostgreSQL, SQLite) has its own implementation of this interface to handle its specific SQL syntax requirements.

type FieldValue

type FieldValue struct {
	// Name is the name of the database field or column
	Name string

	// Value is the value to be assigned to the field, can be of any type
	Value interface{}
}

FieldValue represents a field-value pair used in SQL queries for setting values in INSERT, UPDATE, and other operations. It provides a convenient way to associate a field name with its corresponding value while maintaining type safety.

func NewFV

func NewFV(name string, value interface{}) *FieldValue

NewFV is a shorthand alias for NewFieldValue. It creates a new FieldValue instance with the specified field name and value.

Parameters:

  • name: The name of the database field or column
  • value: The value to be assigned to the field

Returns:

  • *FieldValue: A pointer to the newly created FieldValue instance

Example:

fv := NewFV("status", "active")

func NewFieldValue

func NewFieldValue(name string, value interface{}) *FieldValue

NewFieldValue creates a new FieldValue instance with the specified field name and value. It is the primary constructor for creating field-value pairs.

Parameters:

  • name: The name of the database field or column
  • value: The value to be assigned to the field

Returns:

  • *FieldValue: A pointer to the newly created FieldValue instance

Example:

fv := NewFieldValue("age", 25)
b.Update("users").Set(fv)

func NewKV

func NewKV(name string, value interface{}) *FieldValue

NewKV is a shorthand alias for NewFieldValue. It creates a new FieldValue instance with the specified field name and value. The name 'KV' stands for 'Key-Value'.

Parameters:

  • name: The name of the database field or column
  • value: The value to be assigned to the field

Returns:

  • *FieldValue: A pointer to the newly created FieldValue instance

Example:

fv := NewKV("email", "user@example.com")

type MysqlDialector

type MysqlDialector struct {
	Dialector
}

MysqlDialector implements the Dialector interface for MySQL database. It provides MySQL-specific SQL syntax handling, including backtick escaping for identifiers and ? for parameter placeholders.

func (MysqlDialector) Escape

func (MysqlDialector) Escape(s ...string) string

Escape wraps MySQL identifiers with backticks and handles multiple identifiers by joining them with "`, `".

func (MysqlDialector) GetEscapeChar

func (MysqlDialector) GetEscapeChar() string

GetEscapeChar returns the backtick character used for escaping MySQL identifiers.

func (MysqlDialector) Placeholder

func (MysqlDialector) Placeholder(index int) string

Placeholder returns "?" as the parameter placeholder for MySQL queries.

type PostgresqlDialector

type PostgresqlDialector struct {
	Dialector
}

PostgresqlDialector implements the Dialector interface for PostgreSQL database. It provides PostgreSQL-specific SQL syntax handling, including double quote escaping for identifiers and $n for parameter placeholders.

func (PostgresqlDialector) Escape

func (p PostgresqlDialector) Escape(s ...string) string

Escape wraps PostgreSQL identifiers with double quotes and handles multiple identifiers by joining them with '", "'.

func (PostgresqlDialector) GetEscapeChar

func (p PostgresqlDialector) GetEscapeChar() string

GetEscapeChar returns the double quote character used for escaping PostgreSQL identifiers.

func (PostgresqlDialector) Placeholder

func (p PostgresqlDialector) Placeholder(index int) string

Placeholder returns "$n" as the parameter placeholder for PostgreSQL queries, where n is the parameter index.

type Query

type Query struct {
	// Query holds the parameterized SQL query string with placeholders
	Query string

	// Args holds the parameter values that correspond to the placeholders in Query
	Args []interface{}
}

Query represents a SQL query with its associated parameter values. It provides methods for converting the parameterized query into a string representation with the parameter values interpolated.

The Query type is typically created by calling Build() on a Builder instance and should not be created directly. It encapsulates both the SQL query string and its parameter values to ensure type safety and prevent SQL injection.

Example usage:

b := builder.New()
query, err := b.Select("id", "name").From("users").Where(builder.Eq("status", "active")).Build()
// query can be used with database/sql's Exec or Query methods

func NewQuery

func NewQuery(q string, args ...interface{}) *Query

NewQuery creates a new Query instance with the given SQL query string and parameter values. The query string should use placeholders (?) for parameter values that will be bound when executing the query.

This function is primarily used internally by the Builder's Build method and should rarely be called directly. It ensures that the number of placeholders matches the number of provided arguments.

Parameters:

  • q: The SQL query string with parameter placeholders
  • args: The parameter values that correspond to the placeholders

Returns a new Query instance that can be used with database/sql methods.

func (*Query) String

func (q *Query) String() string

String returns a string representation of the query with parameter values interpolated into the query string. This method is useful for debugging and logging purposes, but should not be used for actual query execution to avoid SQL injection vulnerabilities.

The method performs simple string replacements to create a human-readable version of the query. It handles common SQL operators and placeholders, replacing them with the actual parameter values.

Warning: The returned string may contain unescaped values and should never be executed directly against a database.

Example:

q := NewQuery("SELECT * FROM users WHERE status = ?", "active")
fmt.Println(q.String()) // Outputs: SELECT * FROM users WHERE status = 'active'

type SQLType

type SQLType int

SQLType represents the type of SQL query being constructed. It is used to track and validate the query type during construction.

const (
	// RawSQL represents a raw SQL query that will be used as-is.
	RawSQL SQLType = iota + 1

	// SelectSQL represents a SELECT query for retrieving data.
	SelectSQL

	// InsertSQL represents an INSERT query for adding new records.
	InsertSQL

	// ReplaceSQL represents a REPLACE query (MySQL-specific) for replacing records.
	ReplaceSQL

	// InsertOrUpdateSQL represents an INSERT ... ON DUPLICATE KEY UPDATE query (MySQL-specific).
	InsertOrUpdateSQL

	// UpdateSQL represents an UPDATE query for modifying existing records.
	UpdateSQL

	// DeleteSQL represents a DELETE query for removing records.
	DeleteSQL
)

SQL query types supported by the builder.

type SQLiteDialector

type SQLiteDialector struct {
	Dialector
}

SQLiteDialector implements the Dialector interface for SQLite database. It provides SQLite-specific SQL syntax handling, including double quote escaping for identifiers and ? for parameter placeholders.

func (SQLiteDialector) Escape

func (s SQLiteDialector) Escape(strs ...string) string

Escape wraps SQLite identifiers with double quotes and handles multiple identifiers by joining them with '", "'.

func (SQLiteDialector) GetEscapeChar

func (s SQLiteDialector) GetEscapeChar() string

GetEscapeChar returns the double quote character used for escaping SQLite identifiers.

func (SQLiteDialector) Placeholder

func (s SQLiteDialector) Placeholder(index int) string

Placeholder returns "?" as the parameter placeholder for SQLite queries.

type Values

type Values []interface{}

Values represents a slice of interface{} used for storing query parameter values. It is used throughout the package to handle various types of SQL parameter values in a type-safe manner. This type provides a convenient way to pass multiple values to SQL conditions while maintaining type flexibility.

Example usage:

values := Values{1, "active", true}
// Can be used with IN conditions
b.Select("*").From("users").Where(builder.In("status", values...))

Jump to

Keyboard shortcuts

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