fluentsql

package module
v1.5.4 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2025 License: MIT Imports: 3 Imported by: 5

README

Fluent SQL

Fluent SQL - flexible and powerful SQL string builder for Go

Setup

Install module

# Latest version
go get github.com/jivegroup/fluentsql@latest

# Specific version
go get github.com/jivegroup/fluentsql@v1.3.5

Use module

import (
    qb "github.com/jivegroup/fluentsql"	
)

QueryBuilder

QueryBuilder: SELECT - extracts data from a database

import (
    qb "github.com/jivegroup/fluentsql"	
)

// ------------- Simple query -------------
sql := qb.QueryInstance().
    Select("employee_id", "first_name", "last_name", "department_id").
    From("employees").
    Where("department_id", qb.NotEq, 8).
    OrderBy("first_name", qb.Asc).
    OrderBy("last_name", qb.Asc).
    Limit(3, 0).
    String()

// ------------- Sub-query -------------
sql = qb.QueryInstance().
    Select("employee_id", "first_name", "last_name", "salary").
    From("employees").
    Where("salary", qb.Eq,
        qb.QueryInstance().
            Select("DISTINCT salary").
            From("employees").
            OrderBy("salary", qb.Desc).
            Limit(1, 1),
    ).
    String()

// ------------- Where Group -------------
sql = qb.QueryInstance().
    Select("employee_id", "first_name", "last_name", "salary").
    From("employees").
    Where("salary", qb.In, qb.ValueBetween{
        Low:  9000,
        High: 12000,
    }).
    WhereGroup(func(whereBuilder WhereBuilder) *WhereBuilder {
        whereBuilder.Where("age", qb.Eq, 25).
        WhereOr("work_year", qb.Eq, 10)

        return &whereBuilder
    }),
    String()

// ------------- JOIN query -------------
sql = qb.QueryInstance().
    Select("r.region_name", "c.country_name", "l.street_address", "l.city").
    From("regions", "r").
    Join(qb.LeftJoin, "countries c", qb.Condition{
        Field: "c.region_id",
        Opt:   qb.Eq,
        Value: qb.ValueField("r.region_id"),
    }).
    Join(qb.LeftJoin, "locations l", qb.Condition{
        Field: "l.country_id",
        Opt:   qb.Eq,
        Value: qb.ValueField("c.country_id"),
    }).
    Where("c.country_id", qb.In, []string{"US", "UK", "CN"}).
    String()

// ------------- ALL | ANY -------------
sql = qb.QueryInstance().
    Select("employee_id", "first_name", "last_name", "salary").
    From("employees").
    Where("salary", qb.GrEqAll,
        qb.QueryInstance().
        Select("salary").
        From("employees").
        Where("department_id", qb.Eq, 8),
    ).
	OrderBy("salary", qb.Desc).
    String()

sql = qb.QueryInstance().
    Select("employee_id", "first_name", "last_name", "salary").
    From("employees").
    Where("salary", qb.GreaterAny,
        qb.QueryInstance().
        Select("AVG(salary)").
        From("employees").
        GroupBy("department_id"),
    ).
    OrderBy("first_name", qb.Asc).
    OrderBy("last_name", qb.Asc).
    String()

// ------------- EXISTS -------------
sql = qb.QueryInstance().
    Select("employee_id", "first_name", "last_name", "salary").
    From("employees", " e").
    Where(qb.FieldEmpty(""), qb.Exists,
        qb.QueryInstance().
        Select("1").
        From("dependents", "d").
        Where("d.employee_id", qb.Eq, qb.ValueField("e.employee_id")),
    ).
    OrderBy("first_name", qb.Asc).
    OrderBy("last_name", qb.Asc).
    String()

// ------------- BETWEEN | NOT BETWEEN -------------
sql = qb.QueryInstance().
    Select("employee_id", "first_name", "last_name", "salary").
    From("employees").
    Where("salary", qb.Between, qb.ValueBetween{
        Low:  9000,
        High: 12000,
    }).
    OrderBy("salary", qb.Asc).
    String()

sql = qb.QueryInstance().
    Select("employee_id", "first_name", "last_name", qb.FieldYear("hire_date")+" joined_year").
    From("employees").
    Where(qb.FieldYear("hire_date"),
        qb.Between, 
        qb.ValueBetween{
            Low:  1990,
            High: 1993,
        }).
    OrderBy("hire_date", qb.Asc).
    String()

// ------------- IN | NOT IN -------------
sql = qb.QueryInstance().
    Select("employee_id", "first_name", "last_name", "job_id").
    From("employees").
    Where("job_id", qb.In, []int{8, 9, 10}).
    OrderBy("job_id", qb.Asc).
    String()

sql = qb.QueryInstance().
    Select("employee_id", "first_name", "last_name", "job_id").
    From("employees").
    Where("job_id", qb.NotIn, []int{7, 8, 9}).
    OrderBy("job_id", qb.Asc).
    String()

// ------------- LIKE | NOT LIKE -------------
sql = qb.QueryInstance().
    Select("employee_id", "first_name", "last_name").
    From("employees").
    Where("first_name", qb.Like, "S%").
    Where("first_name", qb.NotLike, "Sh%").
    OrderBy("first_name", qb.Asc).
    String()

// ------------- IS NULL | IS NOT NUL -------------
sql = qb.QueryInstance().
    Select("employee_id", "first_name", "last_name", "phone_number").
    From("employees").
    Where("phone_number", qb.Null, nil).
    String()

sql = qb.QueryInstance().
    Select("employee_id", "first_name", "last_name", "phone_number").
    From("employees").
    Where("phone_number", qb.NotNull, nil).
    String()

// ------------- NOT -------------
sql = qb.QueryInstance().
    Select("employee_id", "first_name", "last_name", "salary").
    From("employees").
    Where("department_id", qb.Eq, 5).
    Where(qb.FieldNot("salary"), qb.Greater, 5000).
    String()

sql = qb.QueryInstance().
    Select("employee_id", "first_name", "last_name", "salary").
    From("employees").
    Where("salary", qb.NotBetween, qb.ValueBetween{Low: 3000, High: 5000}).
    String()

sql = qb.QueryInstance().
    Select("employee_id", "first_name", "last_name").
    From("employees", "e").
    Where(qb.FieldEmpty(""), qb.NotExists,
        qb.QueryInstance().
        Select("employee_id").
        From("dependents", "d").
        Where("d.employee_id", qb.Eq, qb.ValueField("e.employee_id")),
    ).
    String()

UpdateBuilder

UpdateBuilder: UPDATE - updates data in a database

import (
    qb "github.com/jivegroup/fluentsql"
)

// Simple
sql := qb.UpdateInstance().
    Update("employees").
    Set("first_name", "Steven").
    Set("last_name", "King").
    Where("employee_id", qb.Eq, 100).
    String()

// Complex
sql = qb.UpdateInstance().
    Update("employees").
    Set([]string{"first_name", "last_name", "salary", "department_id"}, []any{"Steven - Modified", "King - Modified", 25500, 11}).
    Where("employee_id", qb.Eq, 100).
    String()

InsertBuilder

InsertBuilder: INSERT - inserts new data into a database

import (
    qb "github.com/jivegroup/fluentsql"
)

// Insert multi-rows
sql := qb.InsertInstance().
    Insert("countries", "country_id", "country_name", "region_id").
    Row("VN", "Vietnam", 4).
    Row("VI", "Vieata", 4).
    Row("VM", "VieatMonda", 4).
	String()

// Insert from query
sql = qb.InsertInstance().
    Insert("countries_temp", "country_id", "country_name", "region_id").
    Query(qb.QueryInstance().
        Select("c.country_id", "c.country_name", "c.region_id").
        From("countries", "c").
        Where("c.country_id", qb.NotIn, []string{"VN", "VI", "VM"}),
    ).
    String()

DeleteBuilder

DeleteBuilder: DELETE - deletes data from a database

import (
    qb "github.com/jivegroup/fluentsql"
)

sql := qb.DeleteInstance().
    Delete("countries").
    Where("country_id", qb.Eq, "VN").
    WhereOr("country_id", qb.Eq, "VI").
    WhereOr("country_id", qb.Eq, "VM").
    String()

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (

	// MySQL is a constant representing the MySQL database type.
	MySQL = "MySQL"
	// PostgreSQL is a constant representing the PostgreSQL database type.
	PostgreSQL = "PostgreSQL"
	// SQLite is a constant representing the SQLite database type.
	SQLite = "SQLite"
)

Functions

func IsDialect

func IsDialect(dialectName string) bool

IsDialect checks if the current dialect matches the specified dialect name. Parameters:

  • dialectName (string): The name of the dialect to check (e.g., "MySQL", "PostgreSQL", "SQLite")

Returns:

  • bool: true if the current dialect matches the specified name, false otherwise

func SetDialect

func SetDialect(dialect Dialect)

SetDialect sets the current database dialect for placeholder formatting. Parameters:

  • dialect (Dialect): The database dialect to set as the current one.

Types

type Case

type Case struct {
	// Exp specifies the expression to be evaluated in the CASE statement.
	Exp string
	// WhenClauses is a list of WHEN clauses defined for the CASE statement.
	WhenClauses []WhenCase
	// Name is the alias for the CASE statement.
	Name string
}

func FieldCase

func FieldCase(exp, name string) *Case

FieldCase creates a new Case instance with the provided expression and name.

Parameters:

  • exp: The expression to be evaluated in the CASE clause.
  • name: The alias for the CASE clause.

Returns:

  • *Case: A pointer to a new Case instance.

func (*Case) String

func (c *Case) String() string

String generates the SQL representation of the entire CASE statement.

Returns:

  • string: The SQL string of the CASE statement.

func (*Case) StringArgs

func (c *Case) StringArgs(args []any) (string, []any)

StringArgs generates the SQL CASE statement string and appends the associated arguments to the slice.

Parameters: - args []any: The input slice to which the expression and WHEN clause arguments will be appended.

Returns: - string: The SQL CASE statement string. - []any: The updated slice of arguments, including expression and WHEN clause values.

func (*Case) When

func (c *Case) When(conditions any, value string) *Case

When appends a new WHEN clause to the Case instance.

Parameters:

  • conditions: The condition(s) to evaluate (can be a single value, string, or a slice of Condition).
  • value: The value to return when the condition is met.

Returns:

  • *Case: A pointer to the Case instance, for method chaining.

type Condition

type Condition struct {
	// Field represents the name of the column to compare. It can be of type `string` or `FieldNot`.
	Field any
	// Opt specifies the condition operator such as =, <>, >, <, >=, <=, LIKE, IN, NOT IN, BETWEEN, etc.
	Opt WhereOpt
	// Value holds the value to be compared against the field. Support ValueField for checking with table's column
	Value any
	// AndOr specifies the logical combination with the previous condition (AND, OR). Default is AND.
	AndOr WhereAndOr
	// Group contains sub-conditions enclosed in parentheses `()`.
	Group []Condition
}

Condition type struct

func (*Condition) String

func (c *Condition) String() string

String generates the SQL representation of the Condition.

This function converts the condition into a SQL WHERE clause representation, supporting various SQL operators, subqueries, groups, and field-value conditions.

Returns:

  • string: A SQL string representation of the condition.

func (*Condition) StringArgs

func (c *Condition) StringArgs(args []any) (string, []any)

StringArgs generates the SQL condition string and associated arguments.

Parameters: - args []any: A slice of arguments for building the condition.

Returns: - string: The SQL condition as a string. - []any: A slice containing the arguments used in the condition.

type Delete

type Delete struct {
	Table any    // Table specifies the name of the table to delete data from
	Alias string // Alias represents an optional alias for the table
}

Delete clause

func (*Delete) String

func (u *Delete) String() string

String generates the DELETE SQL query as a string. It constructs the query by including the table name and an optional table alias.

Returns:

  • A string representing the DELETE SQL query.

func (*Delete) StringArgs

func (u *Delete) StringArgs(args []any) (string, []any)

StringArgs generates the DELETE SQL statement as a string and updates the provided arguments.

Parameters:

  • args ([]any): A slice of arguments passed to be used in the query.

Returns:

  • string: The DELETE SQL statement including the table and alias (if present).
  • []any: The updated slice of query arguments.

type DeleteBuilder

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

DeleteBuilder struct represents a builder for constructing DELETE SQL queries.

Syntax:

DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name [[AS] tbl_alias]
[PARTITION (partition_name [, partition_name] ...)]
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]

It defines the components of the DELETE query.

func DeleteInstance

func DeleteInstance() *DeleteBuilder

DeleteInstance creates a new instance of DeleteBuilder.

Returns:

  • *DeleteBuilder: A pointer to the newly created DeleteBuilder instance.

func (*DeleteBuilder) Delete

func (db *DeleteBuilder) Delete(table string, alias ...string) *DeleteBuilder

Delete specifies the table and an optional alias for the DELETE query.

Parameters:

  • table (string): The name of the table from which rows will be deleted.
  • alias (...string): An optional alias for the table.

Returns:

  • *DeleteBuilder: A pointer to the current instance of DeleteBuilder.

func (*DeleteBuilder) Sql

func (db *DeleteBuilder) Sql() (string, []any, error)

Sql generates the DELETE SQL query string and returns it along with its arguments.

Returns:

  • string: The DELETE SQL query string.
  • []any: A slice of arguments used in the query.
  • error: Any error that occurs during query generation.

func (*DeleteBuilder) String

func (db *DeleteBuilder) String() string

String generates the DELETE SQL query as a string.

It constructs the query by combining various parts of the query, including the DELETE clause, WHERE clause, ORDER BY clause, and LIMIT clause.

Returns:

  • A string representing the complete DELETE SQL query.

func (*DeleteBuilder) StringArgs

func (db *DeleteBuilder) StringArgs(args []any) (string, []any, error)

StringArgs constructs and returns the DELETE SQL query string along with its arguments.

Parameters:

  • args ([]any): A slice of arguments passed to be used in the query.

Returns:

  • string: The DELETE SQL query string built from various components.
  • []any: A slice of any type containing the arguments used in the query.
  • error: Any error that may occur during the query construction.

func (*DeleteBuilder) Where

func (db *DeleteBuilder) Where(field any, opt WhereOpt, value any) *DeleteBuilder

Where adds a condition to the WHERE clause using the AND operator.

Parameters:

  • field (any): The field or column involved in the condition.
  • opt (WhereOpt): The comparison operator (e.g., =, !=, >, <).
  • value (any): The value to compare against.

Returns:

  • *DeleteBuilder: A pointer to the current instance of DeleteBuilder.

func (*DeleteBuilder) WhereCondition

func (db *DeleteBuilder) WhereCondition(conditions ...Condition) *DeleteBuilder

WhereCondition appends multiple conditions to the WHERE clause.

Parameters:

  • conditions (...Condition): A variadic parameter of conditions to be added.

Returns:

  • *DeleteBuilder: A pointer to the current instance of DeleteBuilder.

func (*DeleteBuilder) WhereGroup

func (db *DeleteBuilder) WhereGroup(groupCondition FnWhereBuilder) *DeleteBuilder

WhereGroup combines multiple conditions into a grouped WHERE clause.

Parameters:

  • groupCondition (FnWhereBuilder): A function that defines the grouped conditions.

Returns:

  • *DeleteBuilder: A pointer to the current instance of DeleteBuilder.

func (*DeleteBuilder) WhereOr

func (db *DeleteBuilder) WhereOr(field any, opt WhereOpt, value any) *DeleteBuilder

WhereOr adds a condition to the WHERE clause using the OR operator.

Parameters:

  • field (any): The field or column involved in the condition.
  • opt (WhereOpt): The comparison operator (e.g., =, !=, >, <).
  • value (any): The value to compare against.

Returns:

  • *DeleteBuilder: A pointer to the current instance of DeleteBuilder.

type Dialect

type Dialect interface {
	// Name returns the name of the dialect.
	Name() string

	// Placeholder generates a placeholder for a parameter at the given position.
	// For example, MySQL uses "?", PostgreSQL uses "$1", "$2", etc.
	Placeholder(position int) string

	// YearFunction returns the SQL function to extract the year from a date.
	// For example, MySQL uses "YEAR(?)", PostgreSQL uses "DATE_PART('year', ?)"
	YearFunction(field string) string
}

Dialect defines the interface for database-specific SQL generation. Each supported database should implement this interface.

func DefaultDialect

func DefaultDialect() Dialect

DefaultDialect returns the default dialect. This is for backward compatibility.

type Fetch

type Fetch struct {
	// Fetch specifies the number of rows to fetch.
	Fetch int
	// Offset specifies the number of rows to skip before starting to fetch rows.
	Offset int
}

Fetch clause represents a SQL FETCH clause with offset and limit.

func (*Fetch) String

func (f *Fetch) String() string

String generates the SQL FETCH clause as a string.

If either Fetch or Offset is greater than 0, it returns the string in the format: "OFFSET <Offset> ROWS FETCH NEXT <Fetch> ROWS ONLY". Otherwise, it returns an empty string.

Returns:

  • A string representing the SQL FETCH clause.

func (*Fetch) StringArgs

func (f *Fetch) StringArgs(args []any) (string, []any)

StringArgs generates the SQL FETCH NEXT ROWS clause string and appends the fetch and offset values to the arguments slice.

Parameters: - args []any: The input slice to which the fetch and offset values will be appended.

Returns: - string: The SQL FETCH NEXT ROWS clause string. Returns an empty string if both values are zero. - []any: The updated slice of arguments, including fetch and offset values.

type FieldEmpty

type FieldEmpty string

FieldEmpty represents an empty SQL field, often used in conditions like EXISTS or NOT EXISTS.

Example:

  • FieldEmpty to handle condition `WHERE NOT EXISTS (SELECT employee_id FROM dependents)`

func (FieldEmpty) String

func (v FieldEmpty) String() string

String returns the string representation of the FieldEmpty type.

Returns:

  • string: The string value of the FieldEmpty instance.

Usage:

  • This is typically used to generate SQL queries where a placeholder field is required for EXISTS or NOT EXISTS clauses.

type FieldNot

type FieldNot string

FieldNot represents a SQL field prefixed with a NOT for negating conditions.

Methods:

  • String(): Returns the SQL string representation of the negated field.

func (FieldNot) String

func (v FieldNot) String() string

String generates the SQL representation of the FieldNot type.

Returns:

  • string: A string prefixed with "NOT" followed by the field name.

Examples:

  • FieldNot to handle condition `WHERE NOT salary > 5000` So, When build condition Where(qb.FieldNot("salary"), qb.Greater, 5000) to keep SQL string as `NOT salary > 5000`

type FieldYear

type FieldYear string

FieldYear represents a SQL year extraction operation for a given field. It generates the SQL syntax for extracting the year portion from a date field based on the database type.

Example usage:

  • MySQL: YEAR(hire_date) Between 1990 AND 1993
  • PostgreSQL: DATE_PART('year', hire_date) Between 1990 AND 1993
  • SQLite: strftime('%Y', hire_date)

func (FieldYear) String

func (v FieldYear) String() string

String generates the SQL representation of a FieldYear based on the database type.

Returns:

  • string: The SQL string for extracting the year from a date field.

Usage:

  • To use as part of a WHERE clause or SELECT statement.
  • The generated output varies depending on the database type (MySQL, PostgreSQL, SQLite).

func (FieldYear) StringArgs

func (v FieldYear) StringArgs(args []any) (string, []any)

StringArgs generates the SQL representation for extracting a year value from a field and adds the field value to the arguments slice.

Parameters: - args []any: The input slice to which the field value will be appended.

Returns: - string: The SQL representation for the year extraction, customized for the database type. - []any: The updated slice of arguments, including the field value.

type FnWhereBuilder

type FnWhereBuilder func(whereBuilder WhereBuilder) *WhereBuilder

FnWhereBuilder function type Used to group multiple conditions into a WhereBuilder.

Parameters:

  • whereBuilder (WhereBuilder): A WhereBuilder instance to modify.

Returns:

  • *WhereBuilder: The modified instance of WhereBuilder.

type From

type From struct {
	// Table represents the table name or a nested query. It can be of type string or *QueryBuilder.
	Table any
	// Alias defines an alias for the table or query in the SQL statement.
	Alias string
}

From clause

func (*From) String

func (f *From) String() string

String generates the SQL representation of the "FROM" clause. It returns the constructed SQL string for the "FROM" clause.

The Table field supports either a simple table name (string) or a nested query (using a *QueryBuilder). An optional Alias can also be appended to the clause.

func (*From) StringArgs

func (f *From) StringArgs(args []any) (string, []any)

StringArgs generates the SQL FROM clause string and associated arguments.

Parameters: - args []any: A slice of arguments for constructing the query.

Returns: - string: The SQL FROM clause string. - []any: A slice containing the arguments used in the clause.

type GroupBy

type GroupBy struct {
	// Items stores the list of fields that will be grouped by in the query.
	Items []string
}

GroupBy clause

func (*GroupBy) Append

func (g *GroupBy) Append(field ...string)

Append adds one or more fields to the GroupBy clause.

Parameters:

  • field: One or more strings representing the fields to group by.

func (*GroupBy) String

func (g *GroupBy) String() string

String converts the GroupBy clause to its SQL string representation.

Returns:

  • string: The SQL representation of the GroupBy clause. Returns an empty string if no fields are added.

func (*GroupBy) StringArgs

func (g *GroupBy) StringArgs(args []any) (string, []any)

StringArgs generates the SQL GROUP BY clause string.

Parameters: - args []any: The input slice of arguments (unused in this case).

Returns: - string: The SQL GROUP BY clause string. Returns an empty string if no items are present. - []any: The unchanged slice of arguments.

type Having

type Having struct {
	Where
}

Having clause

func (*Having) String

func (w *Having) String() string

String generates the SQL HAVING clause string based on the conditions provided. If there are no conditions, it returns an empty string.

Returns:

string - The generated HAVING clause as a string.

func (*Having) StringArgs

func (w *Having) StringArgs(args []any) (string, []any)

StringArgs generates the SQL HAVING clause string and appends the associated argument values.

Parameters: - args []any: The input slice to which the HAVING condition values will be appended.

Returns: - string: The SQL HAVING clause string, combining conditions with "AND". Returns an empty string if no conditions are present. - []any: The updated slice of arguments, including condition values.

type IValueField added in v1.5.4

type IValueField interface {
	Value() string
}

IValueField represents a field value interface that can be converted to a string value.

The Value() method enables dynamic generation of SQL field values that need custom string formatting. This interface is commonly implemented by custom field types that need to control how they are represented in SQL queries.

Example usage:

type CustomField struct {
	name string
}

func (f CustomField) Value() string {
	return fmt.Sprintf("CUSTOM(%s)", f.name)
}

// Can be used in SQL generation
field := CustomField{name: "test"}
sqlValue := field.Value() // Returns "CUSTOM(test)"

type Insert

type Insert struct {
	Table   string   // Table specifies the name of the table into which the data will be inserted.
	Columns []string // Columns defines the list of column names for the INSERT statement.
}

Insert clause represents an SQL INSERT statement with a table name and columns. Cases: INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country) VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');

INSERT INTO dependents (first_name, last_name, relationship, employee_id) VALUES ('Cameron', 'Bell', 'Child', 192), ('Michelle', 'Bell', 'Child', 192);

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country) SELECT SupplierName, ContactName, Address, City, PostalCode, Country FROM Suppliers;

INSERT INTO Customers (CustomerName, City, Country) SELECT SupplierName, City, Country FROM Suppliers WHERE Country='Germany';

func (*Insert) String

func (i *Insert) String() string

String returns the SQL INSERT statement as a string. It joins the Columns slice with commas and formats it into the SQL syntax. Returns: A string representation of the SQL INSERT statement.

func (*Insert) StringArgs

func (i *Insert) StringArgs(args []any) (string, []any)

StringArgs generates the SQL INSERT statement for a table with specified columns.

Parameters:

  • args []any: A slice of arguments to be used in the statement.

Returns:

  • string: The SQL INSERT statement for the table and columns.
  • []any: The updated slice of arguments.

type InsertBuilder

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

InsertBuilder struct represents a builder for constructing SQL INSERT statements. It contains components for managing the INSERT clause, rows, and query statements.

func InsertInstance

func InsertInstance() *InsertBuilder

InsertInstance creates and returns a new instance of InsertBuilder. It initializes an empty InsertBuilder structure.

Returns:

*InsertBuilder - A new instance of the InsertBuilder structure.

func (*InsertBuilder) Insert

func (ib *InsertBuilder) Insert(table string, columns ...string) *InsertBuilder

Insert sets the table name and column names for the INSERT statement.

Parameters:

  • table string: The name of the table into which the data will be inserted.
  • columns ...string: The column names for the INSERT statement.

Returns:

*InsertBuilder - The updated InsertBuilder instance.

func (*InsertBuilder) Query

func (ib *InsertBuilder) Query(query *QueryBuilder) *InsertBuilder

Query sets a subquery for the INSERT statement.

Parameters:

  • query *QueryBuilder: The subquery to be used in the INSERT statement.

Returns:

*InsertBuilder - The updated InsertBuilder instance.

func (*InsertBuilder) Row

func (ib *InsertBuilder) Row(values ...any) *InsertBuilder

Row appends a new row of values to the INSERT statement.

Parameters:

  • values ...any: The values to be inserted into a new row.

Returns:

*InsertBuilder - The updated InsertBuilder instance.

func (*InsertBuilder) Sql

func (ib *InsertBuilder) Sql() (string, []any, error)

Sql retrieves the SQL INSERT statement and its arguments.

Returns:

  • string: The complete SQL INSERT statement.
  • []any: A slice containing the arguments for the statement.
  • error: An error value (always nil in this implementation).

func (*InsertBuilder) String

func (ib *InsertBuilder) String() string

String constructs and returns the complete SQL INSERT statement as a string. It combines the insertStatement, rowStatement, and queryStatement components.

Returns:

string - A string representation of the SQL INSERT statement.

func (*InsertBuilder) StringArgs

func (ib *InsertBuilder) StringArgs(args []any) (string, []any, error)

StringArgs constructs the SQL INSERT statement along with its arguments.

Parameters:

  • args []any: A slice of arguments to be used in the statement.

Returns:

  • string: The constructed SQL INSERT statement.
  • []any: A slice containing the arguments for the statement.
  • error: An error value (always nil in this implementation).

type InsertQuery

type InsertQuery struct {
	// Query stores any query information, typically expected to be a pointer to QueryBuilder.
	Query any
}

InsertQuery represents a query that can be used as a subquery in an INSERT statement.

func (*InsertQuery) String

func (q *InsertQuery) String() string

String converts the query to a string representation.

Returns:

  • string: The string representation of the query. If the Query is a QueryBuilder, it calls the QueryBuilder's String method; otherwise, it returns an empty string.

func (*InsertQuery) StringArgs

func (q *InsertQuery) StringArgs(args []any) (string, []any)

StringArgs generates the SQL string for the subquery in the INSERT statement.

Parameters:

  • args []any: A slice of arguments to be used in the statement.

Returns:

  • string: The SQL string for the subquery.
  • []any: The updated slice of arguments.

type InsertRow

type InsertRow struct {
	Values []any
}

func (*InsertRow) String

func (ir *InsertRow) String() string

String generates and returns the SQL representation of the row's values.

Returns:

  • string: The string representation of the row's values, formatted as a SQL tuple.

func (*InsertRow) StringArgs

func (ir *InsertRow) StringArgs(args []any) (string, []any)

StringArgs generates the SQL string for a single row of values and updates the arguments slice.

Parameters:

  • args []any: A slice of arguments to be used in the statement.

Returns:

  • string: The string representation of the row's values.
  • []any: The updated slice of arguments.

type InsertRows

type InsertRows struct {
	Rows []InsertRow
}

func (*InsertRows) Append

func (r *InsertRows) Append(values ...any)

Append adds a new row of values to the InsertRows.

Parameters:

  • values ...any: Variadic arguments representing the values of a new row.

func (*InsertRows) String

func (r *InsertRows) String() string

String generates and returns the SQL VALUES clause representation of the InsertRows.

Returns:

  • string: The generated VALUES clause as a string.

func (*InsertRows) StringArgs

func (r *InsertRows) StringArgs(args []any) (string, []any)

StringArgs generates the VALUES clause for the INSERT statement, including all rows.

Parameters:

  • args []any: A slice of arguments to be used in the statement.

Returns:

  • string: The SQL VALUES clause.
  • []any: The updated slice of arguments.

type Join

type Join struct {
	Items []JoinItem
}

Join represents a collection of join statements used in a SQL query. Fields:

  • Items: A slice of JoinItem representing all join statements.

func (*Join) Append

func (j *Join) Append(item JoinItem)

Append adds a new join item to the list of joins.

Parameters:

  • item (JoinItem): The join item to be appended.

func (*Join) String

func (j *Join) String() string

String converts the Join object into a SQL-compatible join string.

Returns:

  • string: A SQL string representing the join clauses. Returns an empty string if there are no join items.

func (*Join) StringArgs

func (j *Join) StringArgs(args []any) (string, []any)

StringArgs generates the SQL JOIN clause string and associated arguments.

Parameters: - args []any: A slice of arguments for constructing the query.

Returns: - string: The SQL JOIN clause string. Returns an empty string if there are no JOIN items. - []any: A slice containing the arguments used in the clause.

type JoinItem

type JoinItem struct {
	Join      JoinType
	Table     string
	Condition Condition
}

JoinItem represents a single join entry in a SQL statement. Fields:

  • Join: The type of join (e.g., InnerJoin, LeftJoin).
  • Table: The table name to join.
  • Condition: The ON clause condition for the join.

type JoinType

type JoinType int
const (
	InnerJoin JoinType = iota
	LeftJoin
	RightJoin
	FullOuterJoin
	CrossJoin
)

type Limit

type Limit struct {
	Limit  int // Limit specifies the maximum number of rows to return.
	Offset int // Offset specifies the starting point for rows to return.
}

Limit clause

func (*Limit) String

func (l *Limit) String() string

String generates the SQL LIMIT and OFFSET clause string. It returns an empty string if both Limit and Offset are zero.

Returns: - string: The SQL LIMIT and OFFSET clause string.

func (*Limit) StringArgs

func (l *Limit) StringArgs(args []any) (string, []any)

StringArgs generates the SQL LIMIT and OFFSET clause strings and appends the limit and offset values to the arguments slice.

Parameters: - args []any: The input slice to which the limit and offset values will be appended.

Returns: - string: The SQL LIMIT and OFFSET clause string. Returns an empty string if both values are zero. - []any: The updated slice of arguments, including limit and offset values.

type MySQLDialect

type MySQLDialect struct{}

MySQLDialect implements the Dialect interface for MySQL.

func (MySQLDialect) Name

func (d MySQLDialect) Name() string

Name returns the name of the MySQL dialect.

func (MySQLDialect) Placeholder

func (d MySQLDialect) Placeholder(_ int) string

Placeholder returns the placeholder for MySQL, which is always "?".

Parameter:

  • position: Parameter position (not used in MySQL)

Returns a string containing the question mark placeholder.

func (MySQLDialect) YearFunction

func (d MySQLDialect) YearFunction(field string) string

YearFunction returns the MySQL-specific function to extract the year from a date.

Parameter:

  • field: The date field or expression to extract the year from

Returns a string containing the MySQL YEAR function call.

type OrderBy

type OrderBy struct {
	Items []SortItem // List of sort items for constructing the ORDER BY clause.
}

OrderBy represents the ORDER BY clause of a SQL query.

Fields: - Items ([]SortItem): A slice of sorting items specifying fields and their respective sorting directions.

func (*OrderBy) Append

func (o *OrderBy) Append(field string, dir OrderByDir)

Append adds a new field and its sorting direction to the ORDER BY clause.

Parameters: - field string: The name of the field to add. - dir OrderByDir: The direction of sorting (Asc or Desc).

func (*OrderBy) String

func (o *OrderBy) String() string

String generates the SQL ORDER BY clause.

Returns: - string: The constructed ORDER BY clause. Returns an empty string if no fields are specified.

func (*OrderBy) StringArgs

func (o *OrderBy) StringArgs(args []any) (string, []any)

StringArgs generates the SQL ORDER BY clause string.

Parameters: - args []any: The input slice of arguments (unused in this case).

Returns: - string: The SQL ORDER BY clause string. Returns an empty string if no items are present. - []any: The unchanged slice of arguments.

type OrderByDir

type OrderByDir int

OrderByDir represents the sorting direction.

Values: - Asc: Ascending order. - Desc: Descending order.

const (
	Asc  OrderByDir = iota // Ascending order.
	Desc                   // Descending order.
)

Constants representing sorting directions.

type PostgreSQLDialect

type PostgreSQLDialect struct{}

PostgreSQLDialect implements the Dialect interface for PostgreSQL.

func (PostgreSQLDialect) Name

func (d PostgreSQLDialect) Name() string

Name returns the name of the PostgreSQL dialect.

func (PostgreSQLDialect) Placeholder

func (d PostgreSQLDialect) Placeholder(position int) string

Placeholder returns the placeholder for PostgreSQL, which is "$n" where n is the position.

Parameter:

  • position: The position of the placeholder (1-based)

Returns a string containing the dollar-prefixed position (e.g. "$1", "$2", etc).

func (PostgreSQLDialect) YearFunction

func (d PostgreSQLDialect) YearFunction(field string) string

YearFunction returns the PostgreSQL-specific function to extract the year from a date.

Parameter:

  • field: The date field or expression to extract the year from

Returns a string containing the PostgreSQL DATE_PART function call.

type QueryBuilder

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

QueryBuilder struct Syntax:

SELECT

[ALL | DISTINCT | DISTINCTROW ]
[HIGH_PRIORITY]
[STRAIGHT_JOIN]
[SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
[SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
select_expr [, select_expr] ...
[into_option]
[FROM table_references
  [PARTITION partition_list]]
[WHERE where_condition]
[GROUP BY {col_name | expr | position}, ... [WITH ROLLUP]]
[HAVING where_condition]
[WINDOW window_name AS (window_spec)
    [, window_name AS (window_spec)] ...]
[ORDER BY {col_name | expr | position}
  [ASC | DESC], ... [WITH ROLLUP]]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
[into_option]
[FOR {UPDATE | SHARE}
    [OF tbl_name [, tbl_name] ...]
    [NOWAIT | SKIP LOCKED]
  | LOCK IN SHARE MODE]
[into_option]

into_option: {
   INTO OUTFILE 'file_name'
       [CHARACTER SET charset_name]
       export_options
 | INTO DUMPFILE 'file_name'
 | INTO var_name [, var_name] ...
}

func QueryInstance

func QueryInstance() *QueryBuilder

QueryInstance creates and returns a new instance of QueryBuilder.

Returns: - *QueryBuilder: A pointer to a new QueryBuilder instance.

func (*QueryBuilder) AS

func (qb *QueryBuilder) AS(alias string) *QueryBuilder

AS sets an alias for the entire QueryBuilder instance.

Parameters: - alias string: The alias to be used.

Returns: - *QueryBuilder: The QueryBuilder instance with an alias.

Examples:

SELECT s.name, (SELECT COUNT(*) FROM product AS p WHERE p.store_id=s.id) AS counter FROM store AS s
SELECT p.* FROM (SELECT first_name, last_name FROM Customers) AS p;

func (*QueryBuilder) Fetch

func (qb *QueryBuilder) Fetch(offset, fetch int) *QueryBuilder

Fetch sets the FETCH clause of the query.

Parameters: - offset int: The number of rows to skip. - fetch int: The number of rows to fetch.

Returns: - *QueryBuilder: The QueryBuilder instance with updated FETCH clause.

func (*QueryBuilder) From

func (qb *QueryBuilder) From(table any, alias ...string) *QueryBuilder

From defines the FROM clause in the query.

Parameters: - table any: The table from which to select data. - alias ...string: Optional alias for the table.

Returns: - *QueryBuilder: The QueryBuilder instance with updated FROM clause.

func (*QueryBuilder) GroupBy

func (qb *QueryBuilder) GroupBy(fields ...string) *QueryBuilder

GroupBy defines the GROUP BY clause of the query.

Parameters: - fields ...string: The fields to group by.

Returns: - *QueryBuilder: The QueryBuilder instance with updated GROUP BY clause.

func (*QueryBuilder) Having

func (qb *QueryBuilder) Having(field any, opt WhereOpt, value any) *QueryBuilder

Having defines the HAVING clause of the query.

Parameters: - field any: The column or expression to apply the condition to. - opt WhereOpt: The operator for the condition (e.g., =, >, <). - value any: The value to compare against.

Returns: - *QueryBuilder: The QueryBuilder instance with updated HAVING clause.

func (*QueryBuilder) Join

func (qb *QueryBuilder) Join(join JoinType, table string, condition Condition) *QueryBuilder

Join adds a join clause to the query.

Parameters: - join JoinType: The type of join (e.g., INNER JOIN, LEFT JOIN). - table string: The table to join. - condition Condition: The ON condition for the join.

Returns: - *QueryBuilder: The QueryBuilder instance with the added JOIN clause.

func (*QueryBuilder) Limit

func (qb *QueryBuilder) Limit(limit, offset int) *QueryBuilder

Limit sets the LIMIT clause of the query.

Parameters: - limit int: The maximum number of rows to return. - offset int: The number of rows to skip.

Returns: - *QueryBuilder: The QueryBuilder instance with updated LIMIT clause.

func (*QueryBuilder) OrderBy

func (qb *QueryBuilder) OrderBy(field string, dir OrderByDir) *QueryBuilder

OrderBy defines the ORDER BY clause of the query.

Parameters: - field string: The field to sort by. - dir OrderByDir: The direction of sorting (ASC or DESC).

Returns: - *QueryBuilder: The QueryBuilder instance with updated ORDER BY clause.

func (*QueryBuilder) RemoveFetch

func (qb *QueryBuilder) RemoveFetch() Fetch

RemoveFetch removes the FETCH clause from the query.

Returns: - Fetch: The removed FETCH clause.

func (*QueryBuilder) RemoveLimit

func (qb *QueryBuilder) RemoveLimit() Limit

RemoveLimit removes the LIMIT clause from the query.

Returns: - Limit: The removed LIMIT clause.

func (*QueryBuilder) Select

func (qb *QueryBuilder) Select(columns ...any) *QueryBuilder

Select defines the SELECT clause of the query.

Parameters: - columns ...any: The columns to be selected in the query.

Returns: - *QueryBuilder: The QueryBuilder instance with updated SELECT clause.

func (*QueryBuilder) Sql

func (qb *QueryBuilder) Sql() (string, []any, error)

Sql constructs the SQL query string and associated arguments. It uses the StringArgs method to combine all query parts (SELECT, FROM, WHERE, etc.).

Returns: - string: The complete SQL query as a string. - []any: A slice of arguments to be used with the query (e.g., for prepared statements). - error: Any error encountered during the query construction.

func (*QueryBuilder) String

func (qb *QueryBuilder) String() string

String converts the QueryBuilder instance to a SQL query string.

Returns: - string: The SQL query string representation of the QueryBuilder.

func (*QueryBuilder) StringArgs

func (qb *QueryBuilder) StringArgs(args []any) (string, []any, error)

StringArgs constructs the SQL query string with placeholders and its associated arguments.

Parameters: - args []any: An initial slice of arguments to be used in the query.

Returns: - string: The complete SQL query as a string with placeholders for arguments. - []any: A slice containing all arguments for the query. - error: Any error encountered during query string construction.

func (*QueryBuilder) Where

func (qb *QueryBuilder) Where(field any, opt WhereOpt, value any) *QueryBuilder

Where adds a condition to the WHERE clause of the query.

Parameters: - field any: The column or expression to apply the condition to. - opt WhereOpt: The operator for the condition (e.g., =, >, <). - value any: The value to compare against.

Returns: - *QueryBuilder: The QueryBuilder instance with updated WHERE clause.

func (*QueryBuilder) WhereCondition

func (qb *QueryBuilder) WhereCondition(conditions ...Condition) *QueryBuilder

WhereCondition appends multiple conditions to the WHERE clause.

Parameters: - conditions ...Condition: Conditions to be added.

Returns: - *QueryBuilder: The QueryBuilder instance with updated WHERE clause.

func (*QueryBuilder) WhereGroup

func (qb *QueryBuilder) WhereGroup(groupCondition FnWhereBuilder) *QueryBuilder

WhereGroup combines multiple conditions into a grouped WHERE clause.

Parameters: - groupCondition FnWhereBuilder: A function that constructs a group of conditions.

Returns: - *QueryBuilder: The QueryBuilder instance with the grouped WHERE clause.

func (*QueryBuilder) WhereOr

func (qb *QueryBuilder) WhereOr(field any, opt WhereOpt, value any) *QueryBuilder

WhereOr adds a condition to the WHERE clause with OR logic.

Parameters: - field any: The column or expression to apply the condition to. - opt WhereOpt: The operator for the condition (e.g., =, >, <). - value any: The value to compare against.

Returns: - *QueryBuilder: The QueryBuilder instance with updated WHERE clause.

type SQLiteDialect

type SQLiteDialect struct{}

SQLiteDialect implements the Dialect interface for SQLite.

func (SQLiteDialect) Name

func (d SQLiteDialect) Name() string

Name returns the name of the SQLite dialect.

func (SQLiteDialect) Placeholder

func (d SQLiteDialect) Placeholder(_ int) string

Placeholder returns the placeholder for SQLite, which is "?".

Parameter:

  • position: Parameter position (not used in SQLite)

Returns a string containing the question mark placeholder.

func (SQLiteDialect) YearFunction

func (d SQLiteDialect) YearFunction(field string) string

YearFunction returns the SQLite-specific function to extract the year from a date.

Parameter:

  • field: The date field or expression to extract the year from

Returns a string containing the SQLite strftime function call for year extraction.

type Select

type Select struct {
	// Columns type string or a QueryBuilder
	Columns []any
}

Select clause

func (*Select) String

func (s *Select) String() string

String generates the SQL SELECT statement based on the columns provided in the Select struct. If no columns are specified, it defaults to "SELECT *".

Returns: - A string representing the constructed SQL SELECT statement.

func (*Select) StringArgs

func (s *Select) StringArgs(args []any) (string, []any)

StringArgs generates the SQL SELECT statement string and associated arguments.

Parameters: - args []any: A slice of arguments for constructing the query.

Returns: - string: The complete SQL SELECT statement as a string. - []any: A slice containing the arguments used in the query.

type SortItem

type SortItem struct {
	Field     string     // The field to sort by.
	Direction OrderByDir // The direction of the sort (Asc or Desc).
}

SortItem defines a single field and its sorting direction for the ORDER BY clause.

Fields: - Field (string): The name of the field to sort by. - Direction (OrderByDir): The direction of sorting (Asc or Desc).

func (*SortItem) Dir

func (o *SortItem) Dir() string

Dir returns the string representation of the sorting direction.

Returns: - string: "ASC" if direction is ascending, "DESC" if direction is descending.

type Update

type Update struct {
	Table any    // Table indicates the target database table to be updated.
	Alias string // Alias represents an alternate name for the table that can be used in the query.
}

Update clause

func (*Update) String

func (u *Update) String() string

String generates the SQL statement for an UPDATE clause.

Returns:

  • A string containing the formatted UPDATE statement.

func (*Update) StringArgs

func (u *Update) StringArgs(args []any) (string, []any)

StringArgs generates the SQL fragment for the UPDATE statement and appends to provided arguments. Parameters: - args: A slice of arguments to be appended to.

Returns: - A formatted SQL UPDATE string. - A slice of arguments.

type UpdateBuilder

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

UpdateBuilder struct

UPDATE [LOW_PRIORITY] [IGNORE] table_reference

SET assignment_list
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]

value:

{expr | DEFAULT}

assignment:

col_name = value

assignment_list:

assignment [, assignment] ...

func UpdateInstance

func UpdateInstance() *UpdateBuilder

UpdateInstance Update Builder constructor

UpdateInstance creates and returns a new instance of UpdateBuilder.

Returns: - *UpdateBuilder: A pointer to a new UpdateBuilder instance.

func (*UpdateBuilder) Set

func (ub *UpdateBuilder) Set(field, value any) *UpdateBuilder

Set adds a key-value pair to the SET clause. Parameters: - field (any): The column to be updated. - value (any): The value to set for the column. Returns: - *UpdateBuilder: The current UpdateBuilder instance.

func (*UpdateBuilder) Sql

func (ub *UpdateBuilder) Sql() (string, []any, interface{})

Sql generates the SQL query string and its corresponding arguments.

func (*UpdateBuilder) String

func (ub *UpdateBuilder) String() string

String generates the SQL query string by concatenating all parts of the query. Returns: - A string containing the complete SQL query.

func (*UpdateBuilder) StringArgs

func (ub *UpdateBuilder) StringArgs() (string, []any, error)

StringArgs constructs the SQL query string and collects the argument values. Returns the SQL query string, the list of arguments, and an error if any occurred.

func (*UpdateBuilder) Update

func (ub *UpdateBuilder) Update(table any, alias ...string) *UpdateBuilder

Update sets the table and optional alias for the UPDATE clause. Parameters: - table (any): The table to be updated. - alias (...string): An optional alias for the table. Returns: - *UpdateBuilder: The current UpdateBuilder instance.

func (*UpdateBuilder) Where

func (ub *UpdateBuilder) Where(field any, opt WhereOpt, value any) *UpdateBuilder

Where adds a condition to the WHERE clause using an AND operator. Parameters: - field (any): The field or column to evaluate. - opt (WhereOpt): The conditional operator (e.g., "=", ">", "<"). - value (any): The value to compare to. Returns: - *UpdateBuilder: The current UpdateBuilder instance.

func (*UpdateBuilder) WhereCondition

func (ub *UpdateBuilder) WhereCondition(conditions ...Condition) *UpdateBuilder

WhereCondition appends multiple conditions directly into the WHERE clause. Parameters: - conditions (...Condition): A variadic list of conditions to append. Returns: - *UpdateBuilder: The current UpdateBuilder instance.

func (*UpdateBuilder) WhereGroup

func (ub *UpdateBuilder) WhereGroup(groupCondition FnWhereBuilder) *UpdateBuilder

WhereGroup combines multiple WHERE conditions into a grouped condition. Parameters: - groupCondition (FnWhereBuilder): A function that defines grouped conditions. Returns: - *UpdateBuilder: The current UpdateBuilder instance.

func (*UpdateBuilder) WhereOr

func (ub *UpdateBuilder) WhereOr(field any, opt WhereOpt, value any) *UpdateBuilder

WhereOr adds a condition to the WHERE clause using an OR operator. Parameters: - field (any): The field or column to evaluate. - opt (WhereOpt): The conditional operator (e.g., "=", ">", "<"). - value (any): The value to compare to. Returns: - *UpdateBuilder: The current UpdateBuilder instance.

type UpdateItem

type UpdateItem struct {
	// Field name of column. Can be of type string or []string.
	Field any
	// Value data associated with the field. These could be of type string, int, ValueField, QueryBuilder, or []any.
	Value any
}

func (*UpdateItem) String

func (s *UpdateItem) String() string

String generates the SQL SET clause for an individual update item.

Returns:

  • A string representing the SET clause for the update field and value.

func (*UpdateItem) StringArgs

func (s *UpdateItem) StringArgs(args []any) (string, []any)

StringArgs generates the SQL fragment for an individual assignment in the SET clause. Parameters: - args: A slice of arguments to be appended to.

Returns: - A formatted SQL string for the assignment. - A slice of arguments.

type UpdateSet

type UpdateSet struct {
	Items []UpdateItem // Items represents a collection of update assignments.
}

func (*UpdateSet) Append

func (s *UpdateSet) Append(field, value any)

Append adds a new update assignment to the Items slice.

Parameters:

  • field: The database field or column to be updated.
  • value: The new value assigned to the field.

func (*UpdateSet) AppendItems

func (s *UpdateSet) AppendItems(items ...UpdateItem)

AppendItems appends multiple update assignments to the Items slice.

Parameters:

  • items: A variadic list of UpdateItem objects to be added.

func (*UpdateSet) String

func (s *UpdateSet) String() string

String generates the SQL SET clause combining all update assignments.

Returns:

  • A string representing the full SET clause of the update statement.

func (*UpdateSet) StringArgs

func (s *UpdateSet) StringArgs(args []any) (string, []any)

StringArgs generates the SQL fragment for the SET clause and appends to provided arguments. Parameters: - args: A slice of arguments to be appended to.

Returns: - A formatted SQL SET string. - A slice of arguments.

type ValueBetween

type ValueBetween struct {
	// Low represents the lower bound of the range.
	Low any
	// High represents the upper bound of the range.
	High any
}

ValueBetween for WhereOpt.Between or WhereOpt.NotBetween - A struct to define a range of values for SQL BETWEEN conditions.

func (ValueBetween) String

func (v ValueBetween) String() string

String generates the SQL representation of the ValueBetween range.

Returns:

  • string: A string representing the range in the format "Low AND High" If the bounds are strings, they are enclosed in single quotes.

Examples:

  • If Low = 1999 and High = 2000, it returns "1999 AND 2000"
  • If Low = "1999-01-01" and High = "2000-12-31", it returns "'1999-01-01' AND '2000-12-31'"

func (ValueBetween) StringArgs

func (v ValueBetween) StringArgs(args []any) (string, []any)

StringArgs generates the SQL representation for a ValueBetween range and appends the Low and High values to the arguments slice.

Parameters: - args []any: The input slice to which the Low and High values will be appended.

Returns: - string: The SQL representation of the range in the format "LOW_PLACEHOLDER AND HIGH_PLACEHOLDER". - []any: The updated slice of arguments, including Low and High values.

type ValueField

type ValueField string

ValueField represents a column/field in a SQL query as a string value.

Methods:

  • String(): Converts the ValueField to its string representation.

func (ValueField) Value added in v1.5.4

func (v ValueField) Value() string

Value converts the ValueField to its string representation.

Returns:

  • string: The string representation of the ValueField.

Examples ValueField to handle condition `WHERE c.column <WhereOpt> c.column_1`

So, When build condition Where("d.employee_id", qb.Eq, qb.ValueField("e.employee_id")) to keep SQL string as
    d.employee_id = e.employee_id
    instead of
    d.employee_id = 'e.employee_id'

type WhenCase

type WhenCase struct {
	// Conditions represents the condition(s) evaluated in the WHEN clause. It can be a string, integer, or slice of Condition.
	Conditions any
	// Value represents the result to return when the conditions are met.
	Value string
}

func (*WhenCase) String

func (c *WhenCase) String() string

String generates the SQL representation of the WHEN clause.

Returns:

  • string: The SQL string of the WHEN clause.

func (*WhenCase) StringArgs

func (c *WhenCase) StringArgs(args []any) (string, []any)

StringArgs generates the SQL WHEN clause string for a CASE statement and appends the value and condition arguments to the slice.

Parameters: - args []any: The input slice to which the value and conditions will be appended.

Returns: - string: The SQL WHEN clause string. - []any: The updated slice of arguments, including value and condition values.

type Where

type Where struct {
	// Conditions represent a slice of Condition structs that define the WHERE clause of a SQL query.
	Conditions []Condition
}

Where clause

func (*Where) Append

func (w *Where) Append(conditions ...Condition)

Append adds one or more Condition instances to the Conditions slice of the Where struct.

Parameters:

  • conditions: One or more Condition instances to be added.

Usage:

w.Append(condition1, condition2, ...)

This function appends the given conditions to the existing Conditions slice.

func (*Where) String

func (w *Where) String() string

String generates and returns the SQL representation of the WHERE clause.

Returns:

  • string: A string containing the SQL WHERE clause. If no conditions are present, it returns an empty string.

Usage:

query := w.String()

Example:

  WHERE clause representation of conditions will be formatted as:
	 WHERE condition1 AND condition2 OR condition3

func (*Where) StringArgs

func (w *Where) StringArgs(args []any) (string, []any)

StringArgs generates the SQL WHERE clause string and associated arguments.

Parameters: - args []any: A slice of arguments for constructing the WHERE clause.

Returns: - string: The complete SQL WHERE clause string. Returns an empty string if no conditions are present. - []any: A slice containing the arguments used in the WHERE clause.

type WhereAndOr

type WhereAndOr int
const (
	And WhereAndOr = iota // Logical AND operator for combining conditions
	Or                    // Logical OR operator for combining conditions
)

type WhereBuilder

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

WhereBuilder struct

func WhereInstance

func WhereInstance() *WhereBuilder

WhereInstance Query builder constructor Returns:

  • *WhereBuilder: A new instance of WhereBuilder.

func (*WhereBuilder) Conditions

func (wb *WhereBuilder) Conditions() []Condition

Conditions retrieves all conditions of the WHERE clause.

Returns:

  • []Condition: A slice containing all conditions in the WHERE clause.

func (*WhereBuilder) String

func (wb *WhereBuilder) String() string

String constructs the WHERE clause as a string.

Returns:

  • string: The string representation of the WHERE clause.

func (*WhereBuilder) StringArgs

func (wb *WhereBuilder) StringArgs(args []any) (string, []any)

StringArgs constructs the WHERE clause as a string with argument placeholders.

Parameters:

  • args ([]any): A slice of arguments to use in the WHERE clause.

Returns:

  • string: The string representation of the WHERE clause with placeholders.
  • []any: The updated slice of arguments.

func (*WhereBuilder) Where

func (wb *WhereBuilder) Where(field any, opt WhereOpt, value any) *WhereBuilder

Where builder Adds a new condition to the WHERE clause with an AND operator.

Parameters:

  • field (any): The field name or expression to be checked.
  • opt (WhereOpt): The operator for the condition (e.g., Eq, Greater).
  • value (any): The value to compare the field against.

Returns:

  • *WhereBuilder: The current instance of WhereBuilder for chaining.

func (*WhereBuilder) WhereCondition

func (wb *WhereBuilder) WhereCondition(conditions ...Condition) *WhereBuilder

WhereCondition appends multiple conditions to the WHERE clause.

Parameters:

  • conditions (...Condition): Multiple Condition objects to append.

Returns:

  • *WhereBuilder: The current instance of WhereBuilder for chaining.

func (*WhereBuilder) WhereGroup

func (wb *WhereBuilder) WhereGroup(groupCondition FnWhereBuilder) *WhereBuilder

WhereGroup combines multiple WHERE conditions into a grouped condition.

Parameters:

  • groupCondition (FnWhereBuilder): Function defining the grouped conditions.

Returns:

  • *WhereBuilder: The current instance of WhereBuilder for chaining.

func (*WhereBuilder) WhereOr

func (wb *WhereBuilder) WhereOr(field any, opt WhereOpt, value any) *WhereBuilder

WhereOr builder Adds a new condition to the WHERE clause with an OR operator.

Parameters:

  • field (any): The field name or expression to be checked.
  • opt (WhereOpt): The operator for the condition (e.g., Eq, Greater).
  • value (any): The value to compare the field against.

Returns:

  • *WhereBuilder: The current instance of WhereBuilder for chaining.

type WhereOpt

type WhereOpt int

WhereOpt defines the operators used in SQL conditions.

const (
	Eq         WhereOpt = iota // Equal to (=)
	NotEq                      // Not equal to (<>)
	Diff                       // Not equal to (!=)
	Greater                    // Greater than (>)
	Lesser                     // Less than (<)
	GrEq                       // Greater than or equal to (>=)
	LeEq                       // Less than or equal to (<=)
	Like                       // Pattern matching (LIKE)
	NotLike                    // Not pattern matching (NOT LIKE)
	In                         // Value in a list (IN)
	NotIn                      // Value not in a list (NOT IN)
	Between                    // Value in a range (BETWEEN)
	NotBetween                 // Value not in a range (NOT BETWEEN)
	Null                       // Null value (IS NULL)
	NotNull                    // Not null value (IS NOT NULL)
	Exists                     // Subquery results exist (EXISTS)
	NotExists                  // Subquery results do not exist (NOT EXISTS)
	EqAny                      // Equal to any value in a subquery (= ANY)
	NotEqAny                   // Not equal to any value in a subquery (<> ANY)
	DiffAny                    // Not equal to any value in a subquery (!= ANY)
	GreaterAny                 // Greater than any value in a subquery (> ANY)
	LesserAny                  // Less than any value in a subquery (< ANY)
	GrEqAny                    // Greater than or equal to any value in a subquery (>= ANY)
	LeEqAny                    // Less than or equal to any value in a subquery (<= ANY)
	EqAll                      // Equal to all values in a subquery (= ALL)
	NotEqAll                   // Not equal to all values in a subquery (<> ALL)
	DiffAll                    // Not equal to all values in a subquery (!= ALL)
	GreaterAll                 // Greater than all values in a subquery (> ALL)
	LesserAll                  // Less than all values in a subquery (< ALL)
	GrEqAll                    // Greater than or equal to all values in a subquery (>= ALL)
	LeEqAll                    // Less than or equal to all values in a subquery (<= ALL)
)

Jump to

Keyboard shortcuts

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