class MysqlFramework::SqlCondition

This class is used to represent a Sql Condition for a column.

Constants

NIL_COMPARISONS

Attributes

value[R]

This method is called to get the value of this condition for prepared statements.

Public Class Methods

new(column:, comparison:, value: nil) click to toggle source

Creates a new SqlCondition using the given parameters.

@raise ArgumentError if comparison is 'IS NULL' and value is not nil @raise ArgumentError if comparison is 'IS NOT NULL' and value is not nil @raise ArgumentError if comparison is neither 'IS NULL' or 'IS NOT NULL' and value is nil

@param column [String] - the name of the column to use in the comparison @param comparison [String] - the MySQL comparison operator to use @param value [Object] - the value to use in the comparison (default nil)

# File lib/mysql_framework/sql_condition.rb, line 20
def initialize(column:, comparison:, value: nil)
  @column = column
  @comparison = comparison

  validate(value)
  @value = value
end

Public Instance Methods

to_s() click to toggle source

This method is called to get the condition as a string for a sql prepared statement

@return [String]

# File lib/mysql_framework/sql_condition.rb, line 31
def to_s
  return "#{@column} #{@comparison.upcase}" if nil_comparison?

  "#{@column} #{@comparison} ?"
end

Private Instance Methods

invalid_nil_value?(value) click to toggle source
# File lib/mysql_framework/sql_condition.rb, line 52
def invalid_nil_value?(value)
  return false if skip_nil_validation?
  nil_comparison? == false && value.nil?
end
invalid_null_condition?(value) click to toggle source
# File lib/mysql_framework/sql_condition.rb, line 48
def invalid_null_condition?(value)
  nil_comparison? && value != nil
end
nil_comparison?() click to toggle source
# File lib/mysql_framework/sql_condition.rb, line 39
def nil_comparison?
  NIL_COMPARISONS.include?(@comparison.upcase)
end
skip_nil_validation?() click to toggle source
# File lib/mysql_framework/sql_condition.rb, line 57
def skip_nil_validation?
  ENV.fetch('MYSQL_FRAMEWORK_SKIP_NIL_VALUE_VALIDATION', 'false').downcase == 'true'
end
validate(value) click to toggle source
# File lib/mysql_framework/sql_condition.rb, line 43
def validate(value)
  raise ArgumentError, "Cannot set value when comparison is #{@comparison}" if invalid_null_condition?(value)
  raise ArgumentError, "Comparison of #{@comparison} requires value to be not nil" if invalid_nil_value?(value)
end