Class: SqlcachedClient::Entity

Inherits:
Object
  • Object
show all
Extended by:
Arel, TreeVisitor
Defined in:
lib/sqlcached_client/entity.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Arel

build_arel

Methods included from TreeVisitor

visit_in_preorder

Constructor Details

#initialize(attributes) ⇒ Entity

Returns a new instance of Entity.

Parameters:

  • attributes (Hash)


15
16
17
18
# File 'lib/sqlcached_client/entity.rb', line 15

def initialize(attributes)
  @attributes = attributes
  define_readers(attributes.keys)
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



12
13
14
# File 'lib/sqlcached_client/entity.rb', line 12

def attributes
  @attributes
end

Class Method Details

.association_namesObject



210
211
212
# File 'lib/sqlcached_client/entity.rb', line 210

def association_names
  registered_associations.map(&:accessor_name)
end

.build_query_treeObject



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/sqlcached_client/entity.rb', line 236

def build_query_tree
  # returns the subtrees (associated classes) of the given entity class
  get_associated_entities = -> (entity) {
    entity.registered_associations.map do |a|
      Module.const_get(a.class_name)
    end
  }

  # function to apply to each node while traversing the tree
  visit = -> (entity, parent, index) {
    entity.server.build_request_item(
      entity.query_id,
      entity.query,
      # query_params
      if parent
        Hash[
          parent.registered_associations[index].join_attributes.map do |j_attr|
            [ j_attr[0], {
              value: j_attr[1],
              type: begin
                if entity.join_constant_value?(j_attr[1])
                  'constant'
                else
                  'parent_attribute'
                end
              end
            } ]
          end
        ]
      else
        nil
      end,
      entity.cache
    ).merge(associations: entity.association_names)
  }

  # builds the result of a visit step
  result_builder = -> (root, subtrees) {
    { root: root, subtrees: subtrees }
  }

  # traverse the tree
  visit_in_preorder(get_associated_entities, visit, result_builder)
end

.cache(seconds = nil) ⇒ Object

Configures the caching timing if a parameter is provided, otherwise returns the value set in the current class or in a superclass. Default value is true.



222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/sqlcached_client/entity.rb', line 222

def cache(seconds = nil)
  if seconds.nil?
    @cache ||
      if superclass = ancestors_lookup(:cache)
        superclass.cache
      else
        true
      end
  else
    @cache = seconds
  end
end

.entity_name(value) ⇒ Object

Sets the name of this entity

Parameters:

  • value (String)


35
36
37
# File 'lib/sqlcached_client/entity.rb', line 35

def entity_name(value)
  @query_id = value
end

.entity_namespace(value = nil) ⇒ Object

Sets a prefix for each entity name, or returns the value previously set if no parameter is given



25
26
27
28
29
30
31
# File 'lib/sqlcached_client/entity.rb', line 25

def entity_namespace(value = nil)
  if value.nil?
    @entity_namespace || try_ancestor(:entity_namespace)
  else
    @entity_namespace = value
  end
end

.has_many(accessor_name, options) ⇒ Object

Defines a ‘has_many’ relationship. Available options are

class_name

Specifies the class of the associated objects, if not given it’s inferred from the accessor_name (singularized + camelized).

where

Specifies how to fill the query template for the associated objects. It’s an hash where each key is a foreign parameter that will be set to the value provided. A special case occours when the value is a Symbol, in this case it represents the value of the attribute named as the symbol. For example, where: { id: :user_id } fills the parameter id of the foreign entity with the value of self.user_id.



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/sqlcached_client/entity.rb', line 143

def has_many(accessor_name, options)
  foreign_class_name =
    if options[:class_name].present?
      options[:class_name]
    else
      accessor_name.to_s.singularize.camelize
    end
  # the query to run to get the data
  association = -> (this, foreign_entity, join_attributes, dry_run) {
    foreign_entity.where(Hash[ join_attributes.map do |attr_names|
      attr_value =
        if this.join_constant_value?(attr_names[1])
          attr_names[1]
        else
          this.send(attr_names[1])
        end
      [ attr_names[0], attr_value ]
    end ], dry_run)
  }
  # get the attributes to define the foreign scope
  join_attributes = (options[:where] || []).to_a
  # memoize the associated resultset
  memoize_var = "@has_many_#{accessor_name}"
  # define the accessor method
  define_method(accessor_name) do |dry_run = false|
    # get the associated entity class
    foreign_entity = Module.const_get(foreign_class_name)
    if dry_run
      association.(self, foreign_entity, join_attributes, true)
    else
      instance_variable_get(memoize_var) ||
        instance_variable_set(memoize_var,
          association.(self, foreign_entity, join_attributes, false))
    end
  end
  # define the setter method
  define_method("#{accessor_name}=") do |array|
    # get the associated entity class
    foreign_entity = Module.const_get(foreign_class_name)
    instance_variable_set(memoize_var,
      Resultset.new(foreign_entity, array))
  end
  # save the newly created association
  register_association(OpenStruct.new({
    accessor_name: accessor_name.to_sym,
    class_name: foreign_class_name,
    join_attributes: join_attributes
  }))
end

.has_one(accessor_name, options) ⇒ Object

Defines a ‘has_one’ relationship. See ‘has_many’ for the available options



195
196
197
198
199
200
201
202
# File 'lib/sqlcached_client/entity.rb', line 195

def has_one(accessor_name, options)
  plural_accessor_name = "s_#{accessor_name}".to_s.pluralize
  class_name = accessor_name.to_s.camelize
  has_many(plural_accessor_name, { class_name: class_name }.merge(options))
  define_method(accessor_name) do
    send(plural_accessor_name).first
  end
end

.is_an_association?(name) ⇒ Boolean

Returns:

  • (Boolean)


215
216
217
# File 'lib/sqlcached_client/entity.rb', line 215

def is_an_association?(name)
  association_names.include?(name.to_sym)
end

.join_constant_value?(value) ⇒ Boolean

Returns:

  • (Boolean)


282
283
284
# File 'lib/sqlcached_client/entity.rb', line 282

def join_constant_value?(value)
  !value.is_a?(Symbol)
end

.load_tree(root_conditions, attachment_name = nil, attachment_conditions = nil) ⇒ Object

Like ‘where’ but loads every associated entity recursively at any level,

with only one interaction with the server

Parameters:

  • root_conditions (Array)


289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/sqlcached_client/entity.rb', line 289

def load_tree(root_conditions, attachment_name = nil,
    attachment_conditions = nil)
  attachments =
    if attachment_name.present?
      build_attachments(attachment_name, attachment_conditions,
        root_conditions.size)
    else
      nil
    end
  server_session do |server, session|
    Resultset.new(
      self,
      server.run_query(
        session,
        server.build_tree_request(build_query_tree, root_conditions,
          attachments)
      ),
      attachments
    )
  end
end

.query(*args, &block) ⇒ Object

Sets the query of this entity if a parameter is provided, otherwise returns the value previously set.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/sqlcached_client/entity.rb', line 51

def query(*args, &block)
  if args.empty?
    @query
  else
    if args[0].is_a?(String)
      @query = args[0].strip
    else
      @query = build_arel(
        args.inject({}) do |acc, param|
          acc.merge(
            param.is_a?(Hash) ? param : Hash[ [[param, nil]] ]
          )
        end,
        block).to_sql
    end
  end
end

.query_idString

Returns the identifier of the query template of the current entity

Returns:

  • (String)


41
42
43
44
45
46
47
# File 'lib/sqlcached_client/entity.rb', line 41

def query_id
  if prefix = entity_namespace.presence
    "#{prefix}::#{@query_id}"
  else
    @query_id
  end
end

.registered_associationsObject



205
206
207
# File 'lib/sqlcached_client/entity.rb', line 205

def registered_associations
  @registered_associations || []
end

.server(config = nil) ⇒ Object

Configures the server of this entity if a parameter is provided, otherwise returns the server object previously set.



71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/sqlcached_client/entity.rb', line 71

def server(config = nil)
  if config.nil?
    @server || try_ancestor(:server)
  else
    @server =
      if config.is_a?(Hash)
        Server.new(config)
      else
        config
      end
  end
end

.server_session(&block) ⇒ Object

Gets a session from the server and yields the passed block



85
86
87
# File 'lib/sqlcached_client/entity.rb', line 85

def server_session(&block)
  server.session(&block)
end

.transaction(&block) ⇒ Object



90
91
92
93
94
95
96
97
98
99
100
# File 'lib/sqlcached_client/entity.rb', line 90

def transaction(&block)
  proxy = ProxyObject.new(self)
  srv_local = server
  session = server.get_session
  proxy.plug_method(:server_session) do |server_session_block|
    instance_exec(srv_local, session, &server_session_block)
  end
  result = proxy.execute(srv_local, session, &block)
  session.finish
  result
end

.where(params, dry_run = false) ⇒ Resultset

Runs the entity query with the provided parameters

Returns:



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
# File 'lib/sqlcached_client/entity.rb', line 104

def where(params, dry_run = false)
  request =
    begin
      paramIterator = -> (parameter) {
        server.build_request_item(query_id, query, parameter, cache)
      }
      if params.is_a?(Array)
        params.map { |p| instance_exec(p, &paramIterator) }
      else
        instance_exec(params, &paramIterator)
      end
    end
  if dry_run
    request
  else
    server_resp =
      server_session do |server, session|
        server.run_query(session, server.build_request(
          request.is_a?(Array) ? request : [request]
        ))
      end
    server_resp.flatten!(1) if server_resp.is_array?
    Resultset.new(self, server_resp)
  end
end

Instance Method Details

#build_associations(max_depth = false) ⇒ Object



386
387
388
# File 'lib/sqlcached_client/entity.rb', line 386

def build_associations(max_depth = false)
  Resultset.new(self.class, [self]).build_associations(max_depth)
end

#define_readers(attr_names) ⇒ Object

Define the readers for the attribute names specified

Parameters:

  • attr_names (Array)


337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/sqlcached_client/entity.rb', line 337

def define_readers(attr_names)
  attr_names.each do |attr_name|
    if respond_to?(attr_name)
      if self.class.is_an_association?(attr_name)
        # lazy instantiate associated records
        association_writer = method("#{attr_name}=")
        association_reader = method(attr_name)
        define_singleton_method(attr_name) do
          association_writer.(attributes[attr_name])
          association_reader.()
        end
      else
        raise "Cannot define accessor: #{attr_name}"
      end
    else
      define_singleton_method(attr_name) do
        attributes[attr_name]
      end
    end
  end
end

#get_association_requestsObject



365
366
367
368
369
# File 'lib/sqlcached_client/entity.rb', line 365

def get_association_requests
  self.class.association_names.map do |a_name|
    send(a_name, true)
  end
end

#get_associationsObject



379
380
381
382
383
# File 'lib/sqlcached_client/entity.rb', line 379

def get_associations
  self.class.association_names.map do |a_name|
    send(a_name)
  end
end

#join_constant_value?(value) ⇒ Boolean

Returns:

  • (Boolean)


360
361
362
# File 'lib/sqlcached_client/entity.rb', line 360

def join_constant_value?(value)
  self.class.join_constant_value?(value)
end

#set_associations_data(associations_data) ⇒ Object



372
373
374
375
376
# File 'lib/sqlcached_client/entity.rb', line 372

def set_associations_data(associations_data)
  self.class.association_names.map.with_index do |a_name, i|
    send("#{a_name}=", associations_data[i])
  end
end

#to_hObject



391
392
393
# File 'lib/sqlcached_client/entity.rb', line 391

def to_h
  attributes
end