Class: Cyrel::Clause::With

Inherits:
Base
  • Object
show all
Defined in:
lib/cyrel/clause/with.rb

Overview

Represents a WITH clause in a Cypher query. Used to project results from one part of a query to the next.

Defined Under Namespace

Classes: RawExpressionString

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*items, distinct: false, where: nil) ⇒ With

Initializes a WITH clause.

Parameters:

  • items (Array<Cyrel::Expression::Base, Object, String, Symbol>)

    Items to project. Similar handling to RETURN items. Can include aliases using ‘AS’, e.g., “count(n) AS node_count”.

  • distinct (Boolean) (defaults to: false)

    Whether to project distinct results.

  • where (Cyrel::Clause::Where, nil) (defaults to: nil)

    An optional WHERE clause to apply after WITH.

Raises:

  • (ArgumentError)


16
17
18
19
20
21
22
23
24
# File 'lib/cyrel/clause/with.rb', line 16

def initialize(*items, distinct: false, where: nil)
  @items = process_items(items.flatten)
  @distinct = distinct
  @where = where # Store the Where clause instance directly
  raise ArgumentError, 'WITH clause requires at least one item.' if @items.empty?
  return if where.nil? || where.is_a?(Cyrel::Clause::Where)

  raise ArgumentError, 'WHERE clause for WITH must be a Cyrel::Clause::Where instance.'
end

Instance Attribute Details

#distinctObject (readonly)

Allow optional WHERE after WITH



8
9
10
# File 'lib/cyrel/clause/with.rb', line 8

def distinct
  @distinct
end

#itemsObject (readonly)

Allow optional WHERE after WITH



8
9
10
# File 'lib/cyrel/clause/with.rb', line 8

def items
  @items
end

#whereObject (readonly)

Allow optional WHERE after WITH



8
9
10
# File 'lib/cyrel/clause/with.rb', line 8

def where
  @where
end

Instance Method Details

#render(query) ⇒ String

Renders the WITH clause, including an optional subsequent WHERE.

Parameters:

  • query (Cyrel::Query)

    The query object for rendering expressions.

Returns:

  • (String)

    The Cypher string fragment for the clause.



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/cyrel/clause/with.rb', line 29

def render(query)
  distinct_str = @distinct ? 'DISTINCT ' : ''
  # Need to handle aliases (AS keyword) properly here.
  # The simple RawIdentifier might not be enough if we need parsing.
  # Let's assume for now items can be strings like "n.name AS name".
  rendered_items = @items.map { |item| render_item(item, query) }.join(', ')

  with_part = "WITH #{distinct_str}#{rendered_items}"
  where_part = @where ? "\n#{@where.render(query)}" : '' # Render WHERE on new line

  "#{with_part}#{where_part}"
end