Class: Zena::Use::QueryNode::Compiler

Inherits:
QueryBuilder::Processor
  • Object
show all
Defined in:
lib/zena/use/query_node.rb

Constant Summary collapse

CORE_CONTEXTS =
%w{parent project section}

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Class Attribute Details

.filter_fieldsObject

Returns the value of attribute filter_fields.



128
129
130
# File 'lib/zena/use/query_node.rb', line 128

def filter_fields
  @filter_fields
end

.fulltext_fieldsObject

Returns the value of attribute fulltext_fields.



128
129
130
# File 'lib/zena/use/query_node.rb', line 128

def fulltext_fields
  @fulltext_fields
end

Instance Attribute Details

#contextObject (readonly)

?



109
110
111
# File 'lib/zena/use/query_node.rb', line 109

def context
  @context
end

Class Method Details

.add_filter_field(key, fld_def) ⇒ Object



130
131
132
# File 'lib/zena/use/query_node.rb', line 130

def add_filter_field(key, fld_def)
  self.filter_fields[key] = fld_def
end

.add_fulltext_field(key, &block) ⇒ Object



134
135
136
# File 'lib/zena/use/query_node.rb', line 134

def add_fulltext_field(key, &block)
  self.fulltext_fields[key] = block
end

Instance Method Details

#apply_scope(scope) ⇒ Object



204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/zena/use/query_node.rb', line 204

def apply_scope(scope)
  case scope
  when 'sub_nodes'
    context[:processing] = :scope
    add_filter("#{field_or_attr('fullpath')} LIKE CONCAT(#{field_or_attr('fullpath', table(main_table, -1))},'/%')")
  when 'home'
    context[:processing] = :scope
    add_filter("#{field_or_attr('fullpath')} LIKE CONCAT(#{insert_bind('current_site.home_node.fullpath')},'/%')")
  else
    super
  end
end

#get_scope_index_field(field_name) ⇒ Object



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/zena/use/query_node.rb', line 231

def get_scope_index_field(field_name)
  return nil if @query.main_class.real_class.column_names.include?(field_name)
  # 1. Try scope index
  klass = @query.main_class
  if index_model = klass.kind_of?(VirtualClass) ? klass.idx_class : nil
    index_model = Zena.resolve_const(index_model) rescue NilClass
    if index_model < Zena::Use::ScopeIndex::IndexMethods && index_model.column_names.include?(field_name)
      table_to_use = add_key_value_table('scope_index', index_model.table_name) do |tbl_name|
        # This block is only executed once (ON clause)
        "#{table('nodes')}.id = #{tbl_name}.node_id"
      end
      "#{table_to_use}.#{field_name}"
    else
      # invalid field_name: ignore
      nil
    end
  else
    nil
  end
end

#need_join_scope?(scope_name) ⇒ Boolean

Special case ‘in site’ that is a noop scope and just avoids the insertion of the default ‘in parent’ scope.

Returns:

  • (Boolean)


532
533
534
# File 'lib/zena/use/query_node.rb', line 532

def need_join_scope?(scope_name)
  scope_name != 'site'
end

#parse_custom_query_argument(key, value) ⇒ Object

******** And maybe overwrite these **********



489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
# File 'lib/zena/use/query_node.rb', line 489

def parse_custom_query_argument(key, value)
  return nil unless value
  super.gsub(/(RELATION_ID|KPATH_VALUE|NODE_ATTR|SECURE_TABLE)\(([^)]+)\)|(REF_DATE|NODE_ID|VISITOR_LANG)/) do
    type, value = $1, $2
    type ||= $3
    case type
    when 'RELATION_ID'
      role = value
      if rel = RelationProxy.find_by_role(role.singularize)
        rel[:id]
      else
        raise ::QueryBuilder::Error.new("Custom query: could not find Relation '#{role}'")
      end
    when 'KPATH_VALUE'
      klass_name = value
      if rel = VirtualClass[klass_name]
        rel.kpath
      else
        raise ::QueryBuilder::Error.new("Custom query kpath: could not find VirtualClass '#{role}'")
      end
    when 'SECURE_TABLE'
      table_name = value
      add_filter "\#{secure_scope('#{table_name}')}"
    when 'NODE_ATTR'
      attribute = value
      if Node.safe_method_type([attribute])
        insert_bind("#{node_name}.#{attribute}")
      else
        # not found: consider it's a property
        insert_bind("#{node_name}.prop[#{attribute.inspect}]")
      end
    when 'REF_DATE'
      context[:ref_date] ? insert_bind(context[:ref_date]) : 'now()'
    when 'NODE_ID'
      insert_bind("#{node_name}.id")
    when 'VISITOR_LANG'
      insert_bind("visitor.lang")
    end
  end
end

#process_attr(attribute) ⇒ Object



217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/zena/use/query_node.rb', line 217

def process_attr(attribute)
  case attribute
  when 'project_id', 'section_id', 'discussion_id'
    # Special accessor
    insert_bind "#{node_name}.get_#{attribute}"
  when 'id', 'parent_id'
    # Not RubyLess safe
    insert_bind "#{node_name}.#{attribute}"
  else
    # Use RubyLess
    super
  end
end

#process_equal(left, right, is_not = nil) ⇒ Object

Handle special case for ‘class = ’ and ‘role = ’ and ‘foo.date =’



351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/zena/use/query_node.rb', line 351

def process_equal(left, right, is_not = nil)
  if (left == [:field, 'class'] || left == [:field, 'klass']) && (right[0] == :field || right[0] == :string)
    if klass = Node.get_class(right.last)
      "#{field_or_attr('kpath')} #{is_not ? '<>' : '='} #{quote(klass.kpath)}"
    else
      raise ::QueryBuilder::Error.new("Unknown class #{right.last.inspect}.")
    end
  elsif left == [:field, 'role'] && (right[0] == :field || right[0] == :string)
    if role = Node.get_role(right[1])
      # FIXME: how to only add table once if the other clause in not an OR ?
      add_table('nodes_roles')
      "(#{table('nodes_roles')}.node_id = #{table('nodes')}.id AND #{table('nodes_roles')}.role_id = #{role.id})"
    end
  elsif left.first == :function && left.last.last == 'date'
    # transform "foo.date = baz"
    # [:function, [:field, "foo"], [:method, "date"]]
    # [:field, baz]
    # ==> into
    # "baz >= foo and foo < baz + 1 day"
    a = left[1]
    b = right
    process([:and, [:<=, b, a], [:<, a, [:+, b, [:interval, [:integer, '1'], 'day']]]])
  else
    process_op(:'=', left, right)
  end
end

#process_field(field_name) ⇒ Object

Overwrite this and take care to check for valid fields.



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/zena/use/query_node.rb', line 257

def process_field(field_name)
  if fld = @query.attributes_alias[field_name]
    # use custom query alias value defined in select clause: 'custom_a AS validation'
    if processing_filter?
      # We need to use the full original clause, except when the clause contains group functions (MAX, MIN, etc).
      # If the clause is too complex, we need to use something simpler or it will break (custom queries).
      "(#{fld})"
    else
      fld
    end
  elsif processing_filter? && map_def = self.class.filter_fields[field_name]
    # Special filter fields such as 'role', 'tag' or 'class'
    if map_def.kind_of?(String)
      return map_def
    elsif table_def = map_def[:table]
      use_name, source, target, filter = table_def
      table_to_use = add_key_value_table(use_name, target, map_def[:key]) do |tbl_name|
        # This block is only executed once
        filter.gsub(
          'TABLE1', table(source)
        ).gsub(
          'TABLE2', tbl_name
        )
      end
    else
      table_to_use = table
    end
    "#{table_to_use}.#{map_def[:key]}"
  elsif %w{id parent_id project_id section_id user_id}.include?(field_name) ||
    (Node.safe_method_type([field_name]) && Node.column_names.include?(field_name))
    "#{table}.#{field_name}"
  elsif @query.tables.include?('links') &&
       (key = field_name[/^l_(.+)$/,1]) &&
       (key == 'id' ||
        Zena::Use::Relations::LINK_ATTRIBUTES.include?(key.to_sym))
    "#{table('links')}.#{key}"
  elsif field_name == 'random'
    Zena::Db.sql_function(field_name, nil)
  else
    # property or real column

    # FIXME !!!! Why does this happen ?
    return nil if @query.main_class.columns.kind_of?(Array)


    column = @query.main_class.columns[field_name]
    if column && column.indexed?
      if column.index == true
        group_name = column.type
      elsif column.index =~ Property::Index::FIELD_INDEX_REGEXP
        # field in nodes
        return "#{table}.#{$1}"
      else
        group_name = column.index
      end

      index_table = @query.main_class.real_class.index_table_name(group_name)

      # We use the add_key_value_table rule to avoid inserting the
      # same index access twice.

      tbl = add_key_value_table(group_name, index_table, field_name) do |tbl_name|
        # This block is only executed once
        on_clause = "#{tbl_name}.node_id = #{table}.id AND #{tbl_name}.key = #{quote(field_name)}"
        if group_name.to_s =~ /^ml_/
          on_clause << " AND #{tbl_name}.lang = #{quote(visitor.lang)}"
        end
        # no need for distinct, the new table makes a 1-1 relation
        # ON CLAUSE
        on_clause
        
      end

      "#{tbl}.value"
    else
      super # raises an error
    end
  end
end

#process_function(arg, method, *args) ⇒ Object



476
477
478
479
480
481
482
483
484
485
486
# File 'lib/zena/use/query_node.rb', line 476

def process_function(arg, method, *args)
  # Resolve scope index fields
  arg, method = resolve_scope_idx_fields(arg, method)
  if method
    arg, method = process(arg), process(method)
    args = [arg] + args.map{|a| process(a)}
    Zena::Db.sql_function(method, *args)
  else
    process(arg)
  end
end

#process_idx_field(scope_field) ⇒ Object



252
253
254
# File 'lib/zena/use/query_node.rb', line 252

def process_idx_field(scope_field)
  scope_field
end

#process_like(left, right, is_not = nil) ⇒ Object

Handle special case for ‘class like ’



379
380
381
382
383
384
385
386
387
388
389
# File 'lib/zena/use/query_node.rb', line 379

def process_like(left, right, is_not = nil)
  if (left == [:field, 'class'] || left == [:field, 'klass']) && right[0] == :field
    if klass = Node.get_class(right[1])
      "#{field_or_attr('kpath')} #{is_not ? 'NOT ' : ''}LIKE #{quote(klass.kpath + '%')}"
    else
      raise ::QueryBuilder::Error.new("Unknown class #{right.last.inspect}.")
    end
  else
    process_op(:like, left, right)
  end
end

#process_match(left, right) ⇒ Object



391
392
393
394
395
396
397
398
399
400
401
# File 'lib/zena/use/query_node.rb', line 391

def process_match(left, right)
  if left[0] == :field
    if proc = self.class.fulltext_fields[left[1]]
      proc.call(self, table, right)
    else
      raise ::QueryBuilder::Error.new("Unknown matching field #{left[1].inspect}.")
    end
  else  
    raise ::QueryBuilder::Error.new("Left argument for 'match' should be a fulltext index type.")
  end
end

#process_not(arg) ⇒ Object

:like, [:field, “class”], [:field, “Image”]


404
405
406
407
408
409
410
# File 'lib/zena/use/query_node.rb', line 404

def process_not(arg)
  if (arg[1] == [:field, 'class'] || arg[1] == [:field, 'klass']) && arg[0] == :like
    process_like(arg[1], arg[2], true)
  else
    super
  end
end

#process_not_equal(left, right) ⇒ Object



342
343
344
345
346
347
348
# File 'lib/zena/use/query_node.rb', line 342

def process_not_equal(left, right)
  if (left == [:field, 'class'] || left == [:field, 'klass']) && (right[0] == :field || right[0] == :string)
    process_equal(left, right, true)
  else
    process_op(:'<>', left, right)
  end
end

#process_param(pagination_key) ⇒ Object

Process pagination parameter



338
339
340
# File 'lib/zena/use/query_node.rb', line 338

def process_param(pagination_key)
  "params[#{pagination_key.to_sym.inspect}]"
end

#resolve_main_class(class_name) ⇒ Object

Resolve ‘main_class’ from a class name.



123
124
125
# File 'lib/zena/use/query_node.rb', line 123

def resolve_main_class(class_name)
  VirtualClass[class_name]
end

#resolve_missing_table(query, table_name, table_alias) ⇒ Object

This is used to avoid finding random indexed objects or links in clauses with and without link filters like this: “image or icon” (‘image’ is a filter in ‘parent’ scope, ‘icon’ is a relation found through links).



539
540
541
542
543
544
545
546
547
548
549
550
# File 'lib/zena/use/query_node.rb', line 539

def resolve_missing_table(query, table_name, table_alias)
  if table_name =~ /^idx_nodes/
    # index tables
    query.where.insert 0, "#{table_alias}.node_id = 0"
  elsif table_name == 'links' || table_name =~ /^idx_/
    # index tables
    query.where.insert 0, "#{table_alias}.id = 0"
  else
    # Raise an error
    super
  end
end

#resolve_scope_idx_fields(arg1, arg2) ⇒ Object



412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# File 'lib/zena/use/query_node.rb', line 412

def resolve_scope_idx_fields(arg1, arg2)
  if arg1.first == :function
    # contact.log_at.year
    # arg1 = [:function, [:field, "tag"], [:method, "created_at"]]
    # arg2 = [:method, "year"]
    class_name = arg1[1][1]
    field_name = arg1[2][1]
    function  = arg2
  elsif arg1[0] == :field && arg2[0] == :method
    # contact.log_at  or  log_at.year
    # arg1 = [:field, "contact"]
    class_name = arg1[1]
    # arg2 = [:method, "name"]
    field_name = arg2[1]
    function   = nil
  else
    return [arg1, arg2]
  end

  scope_idx_field = "#{class_name}_#{field_name}"
  if fld = get_scope_index_field(scope_idx_field)
    return [[:idx_field, fld], function]
  else
    # 2. Try to use relation as scope filter 'hot.title = "xxx"', 'hot.title = "xxx"'
    # Multiple links with hot.id = 334 and hot2.id = 323...
    rel = class_name.sub(/\d$/,'')

    source_kpath = @query.main_class.kpath

    if rel = RelationProxy.find_by_role(rel.singularize, source_kpath)
      table_to_use = add_key_value_table('jnode', 'nodes', class_name) do |tbl_name|
        # This block is only executed once per relation name (once for 'hot', once for 'hot2')
        # TODO: Can we remove this ?
        distinct!
        lnk = add_key_value_table('links', 'links', class_name) do |lt|
          "#{lt}.#{rel.link_side} = #{table(main_table)}.id AND #{lt}.relation_id = #{rel.id}"
        end
        
        %Q{#{tbl_name}.id = #{lnk}.#{rel.other_side}}
      end
      
      # Temporarily move to the remote class
      tbl_alias_bak = context[:table_alias]
      context[:table_alias] = table_to_use
      main_class_bak = @query.main_class
      
        @query.main_class = rel.other_vclass
        fld = process_field(field_name)
        
      # Move back
      @query.main_class = main_class_bak
      context[:table_alias] = tbl_alias_bak
      if fld
        [[:idx_field, fld], function]
      else
        nil
      end
    else
      # not a scope index field
      return [arg1, arg2]
    end
  end
end

#scope_fields(scope) ⇒ Object

Scope current context with previous context. For example:

                        current         previous
['parent_id', 'id'] ==> no1.parent_id = nodes.id


188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/zena/use/query_node.rb', line 188

def scope_fields(scope)
  case scope
  when 'self'
    ['parent_id', 'id']
  when *CORE_CONTEXTS
    last? ? %W{#{scope}_id #{scope}_id} : %W{#{scope}_id id}
  when 'site', main_table
    # not an error, but do not scope
    []
  else
    #if CORE_CONTEXTS.include?(scope)
    # error
    nil
  end
end