Class: Ultrasphinx::Fields

Inherits:
Object show all
Includes:
Singleton, Associations
Defined in:
lib/ultrasphinx/fields.rb

Overview

This is a special singleton configuration class that stores the index field configurations. Rather than using a magic hash and including relevant behavior in Ultrasphinx::Configure and Ultrasphinx::Search, we unify it here.

Constant Summary collapse

TYPE_MAP =
{
  'string' => 'text', 
  'text' => 'text', 
  'integer' => 'integer', 
  'date' => 'date', 
  'datetime' => 'date',
  'timestamp' => 'date',
  'float' => 'float',
  'boolean' => 'integer'
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Associations

#entry_identifies_association?, #get_association, #get_association_model

Constructor Details

#initializeFields

Returns a new instance of Fields.



25
26
27
28
29
# File 'lib/ultrasphinx/fields.rb', line 25

def initialize
  @types = {}
  @classes = Hash.new([])
  @groups = []
end

Instance Attribute Details

#classesObject

Returns the value of attribute classes.



23
24
25
# File 'lib/ultrasphinx/fields.rb', line 23

def classes
  @classes
end

#typesObject

Returns the value of attribute types.



23
24
25
# File 'lib/ultrasphinx/fields.rb', line 23

def types
  @types
end

Instance Method Details

#cast(source_string, field) ⇒ Object



62
63
64
65
66
67
68
69
70
# File 'lib/ultrasphinx/fields.rb', line 62

def cast(source_string, field)
  if types[field] == "date"
    "UNIX_TIMESTAMP(#{source_string})"
  elsif types[field] == "integer"
    source_string # "CAST(#{source_string} AS UNSIGNED)"
  else
    source_string              
  end + " AS #{field}"
end

#configure(configuration) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/ultrasphinx/fields.rb', line 87

def configure(configuration)

  configuration.each do |model, options|        

    klass = model.constantize        
    save_and_verify_type('class_id', 'integer', nil, klass)
    save_and_verify_type('class', 'string', nil, klass)
            
    begin
    
      # Fields are from the model
      # We destructively canonicize them back onto the configuration hash
      options['fields'] = options['fields'].to_a.map do |entry|
        entry = {'field' => entry} unless entry.is_a? Hash

        extract_table_alias!(entry, klass)
        extract_field_alias!(entry, klass)
        
        unless klass.columns_hash[entry['field']]
          # XXX I think this is here for migrations
          Ultrasphinx.say "warning: field #{entry['field']} is not present in #{model}"
        else
          save_and_verify_type(entry['as'], klass.columns_hash[entry['field']].type, entry['sortable'], klass)
          install_facets!(entry, klass)
        end            
      end  
      
      # Joins are whatever they are in the target       
      options['include'].to_a.each do |entry|
        extract_table_alias!(entry, klass)
        extract_field_alias!(entry, klass)
        
        association_model = get_association_model(klass, entry)
        
        save_and_verify_type(entry['as'] || entry['field'], association_model.columns_hash[entry['field']].type, entry['sortable'], klass)
        install_facets!(entry, klass)
      end  
      
      # Regular concats are CHAR, group_concats are BLOB and need to be cast to CHAR
      options['concatenate'].to_a.each do |entry|
        extract_table_alias!(entry, klass)
        save_and_verify_type(entry['as'], 'text', entry['sortable'], klass) 
        install_facets!(entry, klass)
      end          
      
    rescue ActiveRecord::StatementInvalid
      Ultrasphinx.say "warning: model #{model} does not exist in the database yet"
    end  
  end
  
  self
end

#extract_field_alias!(entry, klass) ⇒ Object



148
149
150
151
152
# File 'lib/ultrasphinx/fields.rb', line 148

def extract_field_alias!(entry, klass)
  unless entry['as']    
    entry['as'] = entry['field'] 
  end
end

#extract_table_alias!(entry, klass) ⇒ Object



154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/ultrasphinx/fields.rb', line 154

def extract_table_alias!(entry, klass)
  unless entry['table']
    # Getting run twice; don't know why
    if entry['field'] and entry['field'].include? "."
      # This field is referenced by a table alias
      entry['table'], entry['field'] = entry['field'].split(".")
    else
      klass = get_association_model(klass, entry) if entry_identifies_association?(entry)
      entry['table'] = klass.table_name
    end
  end
end

#groupsObject



31
32
33
34
35
# File 'lib/ultrasphinx/fields.rb', line 31

def groups
  @groups.compact.sort_by do |string| 
    string[/= (.*)/, 1]
  end
end

#install_facets!(entry, klass) ⇒ Object



140
141
142
143
144
145
146
# File 'lib/ultrasphinx/fields.rb', line 140

def install_facets!(entry, klass)
  if entry['facet']
    save_and_verify_type(entry['as'], 'text', nil, klass) # source must be a string
    save_and_verify_type("#{entry['as']}_facet", 'integer', nil, klass)
  end
  entry
end

#null(field) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/ultrasphinx/fields.rb', line 72

def null(field)      
  case types[field]
    when 'text'
      "''"
    when 'integer', 'float'
      "0"
    when 'date'
      "18000" # Midnight on 1/1/1970
    when nil
      raise "Field #{field} is missing"
    else
      raise "Field #{field} does not have a valid type #{types[field]}."
  end + " AS #{field}"
end

#save_and_verify_type(field, new_type, string_sortable, klass) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/ultrasphinx/fields.rb', line 37

def save_and_verify_type(field, new_type, string_sortable, klass)
  # Smoosh fields together based on their name in the Sphinx query schema
  field, new_type = field.to_s, TYPE_MAP[new_type.to_s]

  if types[field]
    # Existing field name; verify its type
    raise ConfigurationError, "Column type mismatch for #{field.inspect}; was already #{types[field].inspect}, but is now #{new_type.inspect}." unless types[field] == new_type
    classes[field] = (classes[field] + [klass]).uniq

  else
    # New field      
    types[field] = new_type
    classes[field] = [klass]

    @groups << case new_type
      when 'float', 'integer'
        "sql_group_column = #{field}"
      when 'date'
        "sql_date_column = #{field}"
      when 'text' 
        "sql_str2ordinal_column = #{field}" if string_sortable
    end
  end
end