Module: HashSql

Defined in:
lib/hash_sql.rb,
lib/hash_sql/version.rb

Constant Summary collapse

VERSION =
"0.0.1"

Class Method Summary collapse

Class Method Details

.select_statement(table, options = {}) ⇒ Hash

Creates a SQL Select Statement

Parameters:

  • table (String)

    The table name to select records from

  • options (Hash) (defaults to: {})

    Additional options for the query

Options Hash (options):

  • fields (Array)

    An array of field names to return in the seach result

  • filter (Hash)

    The filter to use for searching accounts. The key is the field name to set the filter on, and the value is the concatenation of the operator to use for comparison and the value used for comparing. Example: { email: “=‘[email protected]’”}

    AND and ORs: The logical operations between filters can be AND or OR and it could be set by setting the key to either “and:” or “or:” Example: { email: “=‘[email protected]”, and: “=’Nick’” } Will be translated to email=‘[email protected]’ AND firstname = ‘Nick’

    If multiple entries are placed inside an “and:” or “or:” they will “ANDed” or “ORed” together. Example: { email: “=‘[email protected]”, and: “=’Nick’”, lastname: “=‘DS’” } Will be translated to email=‘[email protected]’ AND (firstname = ‘Nick’ AND lastname = ‘DS’)

    Example: { email: “=‘[email protected]”, or: “=’Nick’”, lastname: “=‘DS’” } Will be translated to email=‘[email protected]’ OR (firstname = ‘Nick’ OR lastname = ‘DS’)

    NESTING Example: { email: “=‘[email protected]”, and: “=’Nick’”, or: {lastname: “=‘DS’”} } Will be translated to: email=‘[email protected]’ AND (firstname = ‘Nick’ OR lastname = ‘DS’)

  • :order_by (Hash)

    The order in which the results are returned. The key is the field to order on, and the value is :ASC or :DESC

  • :limit (Number)

    the number of results to return

Returns:

  • (Hash)


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/hash_sql.rb', line 37

def self.select_statement(table, options={})
  fields = options[:fields]
  order_by = options[:order_by]
  limit = options[:limit]
  filter = options[:filter]
  query = "SELECT #{fields.join(',')} FROM #{table}"

  filter_string = " WHERE #{parse_filter(filter, nil, '')}" unless filter.nil?
  order_string = " ORDER BY #{parse_order_by(order_by)}" unless order_by.nil?
  limit_string = " LIMIT #{limit}" unless limit.nil?        
  
  filter_string ||= ''
  order_string ||= ''
  limit_string ||= ''

  query = query + filter_string + order_string + limit_string
end