module Marten::DB::Query::SQL::Sanitizer

Direct including types

Defined in:

marten/db/query/sql/concerns/sanitizer.cr

Instance Method Summary

Instance Method Detail

def sanitize_named_parameters(query : String, params : Hash(String, ::DB::Any), connection : Connection::Base | Nil = nil) #

Prepares a raw SQL query with named parameters for safe execution. This function sanitizes a raw SQL query string that uses named parameters (e.g., :name) and constructs a new query string with placeholders that are compatible with the database connection (if provided). It also rearranges the parameters into an ordered array suitable for passing to the database execution method.

If the number of parameters provided does not match the number of placeholders in the query a Marten::DB::Errors::UnmetQuerySetCondition error will be raised.

Example:

query = "SELECT * FROM users WHERE id = :id AND name = :name"
params = {"id" => 1, "name" => "Alice"}
sanitized_query, sanitized_params = sanitize_named_parameters(query, params)
# => sanitized_query = "SELECT * FROM users WHERE id = $1 AND name = $2" (for PostgreSQL)
# => sanitized_params = [1, "Alice"]

[View source]
def sanitize_positional_parameters(query : String, params : Array(::DB::Any), connection : Connection::Base | Nil = nil) #

Prepares a raw SQL query with positional parameters for safe execution. This function sanitizes a raw SQL query string that uses positional parameters (marked by ?) and constructs a new query string with placeholders that are compatible with the database connection (if provided). It also returns the sanitized parameters in a format suitable for passing to the database execution method.

If the number of parameters provided does not match the number of placeholders in the query a Marten::DB::Errors::UnmetQuerySetCondition error will be raised.

Example:

query = "SELECT * FROM users WHERE id = ? AND name = ?"
params = [1, "Alice"]
sanitized_query, sanitized_params = sanitize_positional_parameters(query, params)
# => sanitized_query = "SELECT * FROM users WHERE id = $1 AND name = $2" (for PostgreSQL)
# => sanitized_params = [1, "Alice"]

[View source]