sql_utils

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: May 5, 2026 License: CC0-1.0 Imports: 7 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildArrayContainsCondition

func BuildArrayContainsCondition(
	csv string,
	column string,
	argIndex int,
	conditions *[]string,
	args *[]interface{},
) (int, error)

BuildArrayContainsCondition builds a SQL condition for a text[] column to check if it contains all of the provided comma-separated values. Example: tags=young,festival

func BuildArrayIlikeCondition

func BuildArrayIlikeCondition(
	csvInput string,
	columnExpr string,
	argIndex int,
	conditions *[]string,
	args *[]interface{},
) (int, error)

func BuildBitmaskCondition

func BuildBitmaskCondition(
	inputStr string,
	columnExpr string,
	label string,
	argIndex int,
	conditions *[]string,
	args *[]interface{},
) (int, error)

BuildBitmaskCondition constructs a SQL bitmask filter from a string of flags.

It supports both a single integer value (e.g., "16") representing a full bitmask, and a comma-separated list of flag indices (e.g., "1,3,5"), which are combined into a single uint64 bitmask using bitwise OR (i.e., 1<<flag).

The resulting condition added to `conditions` has the form:

(columnExpr & $N) = $N

where $N is the placeholder for the bitmask value.

This format is commonly used to match rows where all specified flags are present in the column's stored bitmask value.

Parameters:

  • inputStr: A string representing either a full bitmask (e.g., "16") or individual flag indices (e.g., "1,3,5").
  • columnExpr: The SQL expression to test the bitmask against (e.g., "ed.accessibility_flags").
  • label: A human-readable label for use in error messages (e.g., "accessibility_flags").
  • argIndex: The current index for SQL placeholder numbering (e.g., 1, 2, 3, ...).
  • conditions: A pointer to a slice of strings where the SQL condition will be appended.
  • args: A pointer to a slice of interface{} where the corresponding SQL arguments will be appended.

Returns:

  • The next available placeholder index after inserting the bitmask value.
  • An error if any flag is invalid or out of the 0–63 range.

Example:

inputStr = "1,3,5" → bitmask = 1<<1 | 1<<3 | 1<<5 = 42
columnExpr = "ed.accessibility_flags"
Resulting SQL condition: "(ed.accessibility_flags & $1) = $1"
args = [42]

If inputStr is empty, the function does nothing and returns argIndex unchanged.

func BuildColumnArrayOverlapCondition

func BuildColumnArrayOverlapCondition(
	idsInput interface{},
	expr string,
	argIndex int,
	conditions *[]string,
	args *[]interface{},
) (int, error)

BuildColumnArrayOverlapCondition builds a SQL condition for integer array columns using `&&` (overlap). idsInput can be either a string ("1,2,3") or a []int. expr is the SQL column/expression (e.g., "categories"). argIndex is the placeholder number ($1, $2, ...). conditions is a pointer to the slice of WHERE conditions to append to. args is a pointer to the slice of query arguments to append to.

func BuildColumnInIntCondition

func BuildColumnInIntCondition(
	idsInput interface{},
	expr string,
	argIndex int,
	conditions *[]string,
	args *[]interface{},
) (int, error)

BuildColumnInUuidCondition builds a SQL condition using = ANY($N::uuid[]) for UUIDv7 values.

uuidsInput can be either a comma-separated string of UUIDs (e.g., "uuid1,uuid2,uuid3") or a []string slice of UUIDs. All UUIDs are validated using grains_uuid.IsValidUuidv7.

expr is the SQL column or expression to compare against (e.g., "event_uuid").

argIndex is the placeholder number for the SQL parameter ($1, $2, ...).

conditions is a pointer to a slice of strings where the generated condition will be appended.

args is a pointer to a slice of interface{} where the parsed UUID values will be appended.

Returns the next argument index (argIndex + 1) and an error if any input is invalid.

Example usage:

var conditions []string
var args []interface{}
argIndex := 1

argIndex, err := BuildColumnInUuidCondition("uuid1,uuid2", "event_uuid", argIndex, &conditions, &args)
if err != nil {
    return err
}

This will produce a condition similar to:

(event_uuid = ANY($1::uuid[]))

with args containing ["uuid1", "uuid2"]

func BuildColumnInUuidCondition

func BuildColumnInUuidCondition(
	uuidsInput interface{},
	expr string,
	argIndex int,
	conditions *[]string,
	args *[]interface{},
) (int, error)

func BuildContainedInColumnIntRangeCondition

func BuildContainedInColumnIntRangeCondition(
	inputStr, minCol, maxCol string,
	argIndex int,
	conditions *[]string,
	args *[]interface{},
) (int, error)

BuildContainedInColumnIntRangeCondition builds a SQL condition for a min/max range. - One value: "v BETWEEN COALESCE(minCol,0) AND COALESCE(maxCol,1000)" - Two values: "COALESCE(minCol,0) <= v1 AND COALESCE(maxCol,1000) >= v2"

func BuildGeoRadiusCondition

func BuildGeoRadiusCondition(
	lonStr, latStr, radiusStr, columnExpr string,
	startIndex int,
	conditions *[]string,
	args *[]interface{},
) (int, error)

BuildGeoRadiusCondition adds a PostGIS ST_DWithin condition to the given conditions slice, if all three input strings (lonStr, latStr, radiusStr) are valid and non-empty.

Parameters:

  • lonStr, latStr, radiusStr: string inputs for longitude, latitude, and radius in meters.
  • columnExpr: the SQL expression for the geometry column (e.g., "v.point").
  • startIndex: the starting placeholder index for the SQL arguments.
  • conditions: a pointer to the slice of WHERE conditions to append to.
  • args: a pointer to the slice of SQL arguments.

Returns:

  • nextArgIndex: the next available argument index after this condition.
  • err: any error encountered while parsing the inputs.

func BuildInConditionForStringSlice

func BuildInConditionForStringSlice(
	csvInput string,
	columnExpr string,
	argIndex int,
	conditions *[]string,
	args *[]interface{},
) (int, error)

BuildInConditionForStringSlice builds an SQL IN/ANY condition for a comma-separated string list and adds it as a single array argument for SQL sql.

Parameters:

  • csvInput: A comma-separated string (e.g., "US, IN, CA").
  • columnExpr: The format string for the SQL condition (e.g., "v.country = ANY(%s)").
  • label: The label for the input parameter (not used in query, optional).
  • argIndex: The starting index for SQL placeholders ($1, $2, ...).
  • conditions: Pointer to slice of SQL conditions to append to.
  • args: Pointer to slice of query arguments to append to.

Returns:

  • Updated argument index (incremented by 1 since we pass a single array arg).
  • error if parsing fails.

func BuildIntRangeCondition

func BuildIntRangeCondition(
	minStr, maxStr, column string,
	argIndex int,
	conditions *[]string,
	args *[]interface{},
) (int, error)

BuildIntRangeCondition parses min and max numeric string inputs and appends a SQL condition and arguments to filter a column by a numeric range (e.g., age BETWEEN min AND max).

Parameters:

  • minStr: Minimum value as a string (e.g., "18").
  • maxStr: Maximum value as a string (e.g., "65").
  • column: The column name for the SQL condition (e.g., "age").
  • argIndex: Starting index for SQL placeholders ($1, $2, ...).
  • conditions: Pointer to a slice of WHERE clause conditions to be appended to.
  • args: Pointer to a slice of arguments to be appended to.

Returns:

  • newArgIndex: The updated argument index after adding new placeholders.
  • err: An error if parsing of min/max values fails.

func BuildJSONArrayIntCondition

func BuildJSONArrayIntCondition(
	input string,
	jsonbColumn string,
	jsonIndex int,
	argIndex int,
	conditions *[]string,
	args *[]interface{},
) (int, error)

func BuildLikeConditions

func BuildLikeConditions(inputStr, field string, argIndex int, conditions *[]string, args *[]interface{}) (int, error)

BuildLikeConditions parses a comma-separated string of search patterns and appends an ILIKE condition to the provided slices for use in SQL WHERE clauses.

Parameters:

  • inputStr: A comma-separated list of search terms (e.g., "art,design").
  • field: The SQL column to apply the ILIKE condition to (e.g., "title").
  • argIndex: The starting index for SQL placeholders ($1, $2, etc.).
  • conditions: A pointer to a slice of condition strings (modified in place).
  • args: A pointer to a slice of SQL argument values (modified in place).

Behavior:

  • Wildcard `*` in inputStr will be converted to SQL wildcard `%`.
  • Each value becomes a `field ILIKE $N` clause, joined by `OR`.
  • The final condition is wrapped in parentheses: e.g., `(title ILIKE $1 OR title ILIKE $2)`.

Returns:

  • The next available SQL argument index after all patterns.
  • An error if input is malformed (currently always nil).

func BuildLimitOffsetClause

func BuildLimitOffsetClause(limitStr, offsetStr string, startIndex int, args *[]interface{}) (string, int, error)

BuildLimitOffsetClause parses limit and offset strings into integers, validates them, and appends the appropriate LIMIT and OFFSET clauses and arguments to the provided args slice.

Parameters:

  • limitStr: Query string for limit (may be empty).
  • offsetStr: Query string for offset (may be empty).
  • startIndex: Index for SQL placeholders ($N).
  • args: Pointer to the slice of arguments to be extended.

Returns:

  • clause: A SQL clause like "LIMIT $1 OFFSET $2", or just one part.
  • newIndex: The updated index after adding args.
  • err: A validation error, if any.

func BuildPriceCondition

func BuildPriceCondition(
	priceStr,
	priceTypeField, currencyField, minPriceField, maxPriceField,
	label string,
	argIndex int,
	conditions *[]string,
	args *[]interface{},
) (int, error)

func BuildSanitizedIlikeCondition

func BuildSanitizedIlikeCondition(
	inputStr string,
	columnExpr string,
	label string,
	argIndex int,
	conditions *[]string,
	args *[]interface{},
) (int, error)

BuildSanitizedIlikeCondition sanitizes a search string and appends an ILIKE condition and corresponding argument to the provided slices.

Parameters:

  • inputStr: The raw input string (e.g., from query param).
  • columnExpr: SQL expression (e.g., "e.title" or "v.city").
  • label: A descriptive name for error messages (e.g., "title", "city").
  • argIndex: The index to start SQL placeholders at ($1, $2, ...).
  • conditions: Pointer to slice of SQL conditions.
  • args: Pointer to slice of SQL arguments.

Returns:

  • argIndex: The next placeholder index after appending.
  • error: If sanitization fails.

func BuildSanitizedSearchCondition

func BuildSanitizedSearchCondition(
	inputStr string,
	columnExpr string,
	label string,
	argIndex int,
	conditions *[]string,
	args *[]interface{},
) (int, error)

func BuildTimeCondition

func BuildTimeCondition(
	timeStr, field, label string,
	argIndex int,
	conditions *[]string,
	args *[]interface{},
) (int, error)

BuildTimeCondition parses a flexible time range string and appends a SQL BETWEEN condition to the provided conditions and args slices. It returns the updated argument index.

Parameters:

  • timeStr: A comma-separated string with two times (e.g., "9,1730").
  • field: The SQL field to apply the condition to.
  • label: A human-readable label for error reporting.
  • argIndex: The starting index for SQL parameter placeholders ($N).
  • conditions: Pointer to the slice of condition strings to append to.
  • args: Pointer to the slice of SQL arguments to append to.

Returns:

  • newArgIndex: The next available argument index after appending.
  • err: An error if input is invalid or cannot be parsed.

func SanitizeSearchPattern

func SanitizeSearchPattern(input string) (string, error)

SanitizeSearchPattern sanitizes a search pattern by handling wildcard characters and ensuring that the pattern is safe for use in SQL sql.

It processes the input string to:

  • Escape literal asterisks (`\*`), replacing them with a placeholder before converting.
  • Replace unescaped asterisks (`*`) with the SQL wildcard `%`.
  • Restore literal asterisks from the placeholder back to `*`.
  • Reject patterns with too many wildcards (e.g., "%%") or leading wildcards.

Parameters:

  • input: The search pattern string that needs to be sanitized. This can include asterisks (`*`), which will be treated as SQL wildcards. If empty, it returns an empty string without error.

Returns:

  • A sanitized version of the input string, where unsafe or invalid patterns are modified or rejected.
  • An error if the sanitized pattern contains too many wildcards or any other dangerous patterns.

Errors:

  • If the pattern contains too many `%` symbols (e.g., `%%` or patterns with leading wildcards), an error will be returned with the message "too many wildcards in city filter".

Example Usage:

sanitizedPattern, err := SanitizeSearchPattern("New*York")
if err != nil {
  // handle error
}

Types

This section is empty.

Jump to

Keyboard shortcuts

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