Documentation
¶
Overview ¶
Package sqlquery provides a fluent API for building SQL queries with support for MySQL, PostgreSQL, and SQLite.
The package wraps github.com/huandu/go-sqlbuilder and provides simplified query building functions with support for advanced filtering, pagination, and row locking.
Basic Usage ¶
Build a SELECT query with filters:
options := NewFindAllOptions(MySQLFlavor).
WithFilter("status", "active").
WithFilter("age.gte", 18).
WithLimit(10).
WithOffset(0).
WithOrderBy("created_at DESC")
sql, args := FindAllQuery("users", options)
Filter Syntax ¶
The Filters map supports special operators via dot notation:
"field" - Equality (field = value) "field.in" - IN clause (value must be comma-separated string) "field.notin" - NOT IN clause (value must be comma-separated string) "field.not" - Not equal (field != value) "field.gt" - Greater than (field > value) "field.gte" - Greater or equal (field >= value) "field.lt" - Less than (field < value) "field.lte" - Less or equal (field <= value) "field.like" - LIKE pattern matching "field.null" - IS NULL / IS NOT NULL (value must be bool)
Supported Database Flavors ¶
Use one of the predefined flavors when creating options:
MySQLFlavor - MySQL and MariaDB PostgreSQLFlavor - PostgreSQL SQLiteFlavor - SQLite
Index ¶
- func DeleteQuery(flavor Flavor, tableName string, id interface{}) (string, []interface{})
- func DeleteWithOptionsQuery(tableName string, options *DeleteOptions) (string, []interface{})
- func FindAllQuery(tableName string, options *FindAllOptions) (string, []interface{})
- func FindQuery(tableName string, options *FindOptions) (string, []interface{})
- func InsertQuery(flavor Flavor, tag, tableName string, structValue interface{}) (string, []interface{})
- func UpdateQuery(flavor Flavor, tag, tableName string, id interface{}, structValue interface{}) (string, []interface{})
- func UpdateWithOptionsQuery(tableName string, options *UpdateOptions) (string, []interface{})
- type DeleteOptions
- type FindAllOptions
- func (f *FindAllOptions) WithFields(fields []string) *FindAllOptions
- func (f *FindAllOptions) WithFilter(field string, value interface{}) *FindAllOptions
- func (f *FindAllOptions) WithForUpdate(mode string) *FindAllOptions
- func (f *FindAllOptions) WithLimit(limit int) *FindAllOptions
- func (f *FindAllOptions) WithOffset(offset int) *FindAllOptions
- func (f *FindAllOptions) WithOrderBy(orderBy string) *FindAllOptions
- type FindOptions
- type Flavor
- type UpdateOptions
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DeleteQuery ¶
DeleteQuery builds a DELETE query and returns the compiled SQL string and arguments.
The function deletes a record identified by its ID.
Parameters:
- flavor: The SQL dialect (MySQLFlavor, PostgreSQLFlavor, or SQLiteFlavor)
- tableName: The name of the table to delete from
- id: The ID value for the WHERE id = ? condition
Returns the compiled SQL string and a slice of arguments for parameterized queries.
Example:
sql, args := DeleteQuery(MySQLFlavor, "users", 123) // DELETE FROM users WHERE id = ?
func DeleteWithOptionsQuery ¶ added in v1.3.0
func DeleteWithOptionsQuery(tableName string, options *DeleteOptions) (string, []interface{})
DeleteWithOptionsQuery builds a DELETE query with custom filter conditions.
This function provides more flexibility than DeleteQuery by allowing:
- Multiple WHERE conditions with filter operators
- Deleting multiple records matching complex criteria
Parameters:
- tableName: The name of the table to delete from
- options: Configuration including flavor and filter conditions
Returns the compiled SQL string and a slice of arguments for parameterized queries.
Example:
options := NewDeleteOptions(MySQLFlavor).
WithFilter("status", "inactive").
WithFilter("created_at.lt", time.Now().AddDate(-1, 0, 0))
sql, args := DeleteWithOptionsQuery("users", options)
// DELETE FROM users WHERE status = ? AND created_at < ?
func FindAllQuery ¶
func FindAllQuery(tableName string, options *FindAllOptions) (string, []interface{})
FindAllQuery builds a SELECT query with pagination and returns the compiled SQL string and arguments.
This function extends FindQuery with support for LIMIT, OFFSET, and ORDER BY clauses.
Parameters:
- tableName: The name of the table to query
- options: Configuration including flavor, fields, filters, limit, offset, ordering, and FOR UPDATE settings
Returns the compiled SQL string and a slice of arguments for parameterized queries.
Example:
options := NewFindAllOptions(MySQLFlavor).
WithFilter("status", "active").
WithLimit(10).
WithOffset(20).
WithOrderBy("created_at DESC")
sql, args := FindAllQuery("users", options)
// SELECT * FROM users WHERE status = ? ORDER BY created_at DESC LIMIT 10 OFFSET 20
func FindQuery ¶
func FindQuery(tableName string, options *FindOptions) (string, []interface{})
FindQuery builds a SELECT query and returns the compiled SQL string and arguments.
The function supports filtering with special operators, field selection, and row locking (FOR UPDATE).
Parameters:
- tableName: The name of the table to query
- options: Configuration including flavor, fields, filters, and FOR UPDATE settings
Returns the compiled SQL string and a slice of arguments for parameterized queries.
Example:
options := NewFindOptions(MySQLFlavor).
WithFields([]string{"id", "name", "email"}).
WithFilter("status", "active").
WithFilter("age.gte", 18)
sql, args := FindQuery("users", options)
// SELECT id, name, email FROM users WHERE status = ? AND age >= ?
func InsertQuery ¶
func InsertQuery(flavor Flavor, tag, tableName string, structValue interface{}) (string, []interface{})
InsertQuery builds an INSERT query from a struct and returns the compiled SQL string and arguments.
The function uses struct tags to map struct fields to database columns. Fields are extracted based on the specified tag name (e.g., "db", "sql", or custom tags).
Parameters:
- flavor: The SQL dialect (MySQLFlavor, PostgreSQLFlavor, or SQLiteFlavor)
- tag: The struct tag name to use for field mapping (e.g., "db", "sql")
- tableName: The name of the table to insert into
- structValue: The struct instance containing values to insert
Returns the compiled SQL string and a slice of arguments for parameterized queries.
Example:
type User struct {
Name string `db:"name"`
Email string `db:"email"`
Age int `db:"age"`
}
user := User{Name: "John", Email: "john@example.com", Age: 30}
sql, args := InsertQuery(MySQLFlavor, "db", "users", user)
// INSERT INTO users (name, email, age) VALUES (?, ?, ?)
func UpdateQuery ¶
func UpdateQuery(flavor Flavor, tag, tableName string, id interface{}, structValue interface{}) (string, []interface{})
UpdateQuery builds an UPDATE query from a struct and returns the compiled SQL string and arguments.
The function updates a record identified by its ID. Struct tags determine which fields to update.
Parameters:
- flavor: The SQL dialect (MySQLFlavor, PostgreSQLFlavor, or SQLiteFlavor)
- tag: The struct tag name to use for field mapping (e.g., "db", "sql")
- tableName: The name of the table to update
- id: The ID value for the WHERE id = ? condition
- structValue: The struct instance containing updated values
Returns the compiled SQL string and a slice of arguments for parameterized queries.
Example:
type User struct {
Name string `db:"name"`
Email string `db:"email"`
Age int `db:"age"`
}
user := User{Name: "John", Email: "john@example.com", Age: 31}
sql, args := UpdateQuery(MySQLFlavor, "db", "users", 123, user)
// UPDATE users SET name = ?, email = ?, age = ? WHERE id = ?
func UpdateWithOptionsQuery ¶ added in v1.3.0
func UpdateWithOptionsQuery(tableName string, options *UpdateOptions) (string, []interface{})
UpdateWithOptionsQuery builds an UPDATE query with custom field assignments and filters.
This function provides more flexibility than UpdateQuery by allowing:
- Custom field assignments (not limited to struct fields)
- Multiple WHERE conditions with filter operators
- Updating multiple records at once
Parameters:
- tableName: The name of the table to update
- options: Configuration including flavor, field assignments, and filter conditions
Returns the compiled SQL string and a slice of arguments for parameterized queries.
Example:
options := NewUpdateOptions(MySQLFlavor).
WithAssignment("status", "inactive").
WithAssignment("updated_at", time.Now()).
WithFilter("last_login.lt", time.Now().AddDate(0, -6, 0))
sql, args := UpdateWithOptionsQuery("users", options)
// UPDATE users SET status = ?, updated_at = ? WHERE last_login < ?
Types ¶
type DeleteOptions ¶ added in v1.3.0
DeleteOptions configures the behavior of DeleteWithOptionsQuery for building DELETE queries.
Fields:
- Flavor: The SQL dialect (MySQLFlavor, PostgreSQLFlavor, or SQLiteFlavor)
- Filters: WHERE conditions using field names and optional operators (see package docs for filter syntax)
func NewDeleteOptions ¶ added in v1.3.0
func NewDeleteOptions(flavor Flavor) *DeleteOptions
NewDeleteOptions creates a new DeleteOptions with default values. An empty filters map is initialized.
func (*DeleteOptions) WithFilter ¶ added in v1.3.0
func (d *DeleteOptions) WithFilter(field string, value interface{}) *DeleteOptions
WithFilter returns a new DeleteOptions with an additional filter condition. Supports special operators via dot notation (e.g., "age.gte", "status.in"). See package documentation for complete filter syntax.
type FindAllOptions ¶
type FindAllOptions struct {
Flavor Flavor
Fields []string
Filters map[string]interface{}
Limit int
Offset int
OrderBy string
ForUpdate bool
ForUpdateMode string
}
FindAllOptions configures the behavior of FindAllQuery for building paginated SELECT queries.
Fields:
- Flavor: The SQL dialect (MySQLFlavor, PostgreSQLFlavor, or SQLiteFlavor)
- Fields: Column names to select (defaults to "*" for all columns)
- Filters: WHERE conditions using field names and optional operators (see package docs for filter syntax)
- Limit: Maximum number of rows to return
- Offset: Number of rows to skip before returning results
- OrderBy: ORDER BY clause (e.g., "created_at DESC", "name ASC, id DESC")
- ForUpdate: Whether to add FOR UPDATE clause for row locking
- ForUpdateMode: Optional mode for FOR UPDATE (e.g., "NOWAIT", "SKIP LOCKED")
func NewFindAllOptions ¶
func NewFindAllOptions(flavor Flavor) *FindAllOptions
NewFindAllOptions creates a new FindAllOptions with default values. The fields list defaults to ["*"] (all columns), and an empty filters map is initialized.
func (*FindAllOptions) WithFields ¶
func (f *FindAllOptions) WithFields(fields []string) *FindAllOptions
WithFields returns a new FindAllOptions with the specified field list. Use this to select specific columns instead of "*".
func (*FindAllOptions) WithFilter ¶
func (f *FindAllOptions) WithFilter(field string, value interface{}) *FindAllOptions
WithFilter returns a new FindAllOptions with an additional filter condition. Supports special operators via dot notation (e.g., "age.gte", "status.in"). See package documentation for complete filter syntax.
func (*FindAllOptions) WithForUpdate ¶ added in v1.1.0
func (f *FindAllOptions) WithForUpdate(mode string) *FindAllOptions
WithForUpdate returns a new FindAllOptions with FOR UPDATE clause enabled. The mode parameter can specify locking behavior (e.g., "NOWAIT", "SKIP LOCKED"). Pass an empty string for default FOR UPDATE behavior.
func (*FindAllOptions) WithLimit ¶
func (f *FindAllOptions) WithLimit(limit int) *FindAllOptions
WithLimit returns a new FindAllOptions with the specified LIMIT value.
func (*FindAllOptions) WithOffset ¶
func (f *FindAllOptions) WithOffset(offset int) *FindAllOptions
WithOffset returns a new FindAllOptions with the specified OFFSET value.
func (*FindAllOptions) WithOrderBy ¶
func (f *FindAllOptions) WithOrderBy(orderBy string) *FindAllOptions
WithOrderBy returns a new FindAllOptions with the specified ORDER BY clause. The orderBy parameter should be a valid SQL ORDER BY expression (e.g., "created_at DESC").
type FindOptions ¶
type FindOptions struct {
Flavor Flavor
Fields []string
Filters map[string]interface{}
ForUpdate bool
ForUpdateMode string
}
FindOptions configures the behavior of FindQuery for building SELECT queries.
Fields:
- Flavor: The SQL dialect (MySQLFlavor, PostgreSQLFlavor, or SQLiteFlavor)
- Fields: Column names to select (defaults to "*" for all columns)
- Filters: WHERE conditions using field names and optional operators (see package docs for filter syntax)
- ForUpdate: Whether to add FOR UPDATE clause for row locking
- ForUpdateMode: Optional mode for FOR UPDATE (e.g., "NOWAIT", "SKIP LOCKED")
func NewFindOptions ¶
func NewFindOptions(flavor Flavor) *FindOptions
NewFindOptions creates a new FindOptions with default values. The fields list defaults to ["*"] (all columns), and an empty filters map is initialized.
func (*FindOptions) WithFields ¶
func (f *FindOptions) WithFields(fields []string) *FindOptions
WithFields returns a new FindOptions with the specified field list. Use this to select specific columns instead of "*".
func (*FindOptions) WithFilter ¶
func (f *FindOptions) WithFilter(field string, value interface{}) *FindOptions
WithFilter returns a new FindOptions with an additional filter condition. Supports special operators via dot notation (e.g., "age.gte", "status.in"). See package documentation for complete filter syntax.
func (*FindOptions) WithForUpdate ¶ added in v1.4.0
func (f *FindOptions) WithForUpdate(mode string) *FindOptions
WithForUpdate returns a new FindOptions with FOR UPDATE clause enabled. The mode parameter can specify locking behavior (e.g., "NOWAIT", "SKIP LOCKED"). Pass an empty string for default FOR UPDATE behavior.
type Flavor ¶
type Flavor int
Flavor represents the SQL dialect used for query compilation. It controls the format of compiled SQL to match database-specific syntax.
type UpdateOptions ¶ added in v1.3.0
type UpdateOptions struct {
Flavor Flavor
Assignments map[string]interface{}
Filters map[string]interface{}
}
UpdateOptions configures the behavior of UpdateWithOptionsQuery for building UPDATE queries.
Fields:
- Flavor: The SQL dialect (MySQLFlavor, PostgreSQLFlavor, or SQLiteFlavor)
- Assignments: Field-value pairs to set (e.g., {"status": "active", "updated_at": time.Now()})
- Filters: WHERE conditions using field names and optional operators (see package docs for filter syntax)
func NewUpdateOptions ¶ added in v1.3.0
func NewUpdateOptions(flavor Flavor) *UpdateOptions
NewUpdateOptions creates a new UpdateOptions with default values. Empty maps are initialized for both assignments and filters.
func (*UpdateOptions) WithAssignment ¶ added in v1.3.0
func (u *UpdateOptions) WithAssignment(field string, value interface{}) *UpdateOptions
WithAssignment returns a new UpdateOptions with an additional field assignment. Use this to specify which fields to update and their new values.
func (*UpdateOptions) WithFilter ¶ added in v1.3.0
func (u *UpdateOptions) WithFilter(field string, value interface{}) *UpdateOptions
WithFilter returns a new UpdateOptions with an additional filter condition. Supports special operators via dot notation (e.g., "age.gte", "status.in"). See package documentation for complete filter syntax.