title: Arel: I get "stack level too deep" error when I try to get SQL from Arel
body: <p>First I'd like to describe idea of what I am trying to do. I have &quot;jobstat_jobs&quot; table where I store the information about computing job perfomance. I am trying to compose 2 queries: 1) jobs grouped by project 2) jobs grouped by project and state. Then these queries are inner joined and I want to display share of jobs of each state among all jobs. I implemented it using ActiveRecord and raw sql, but I can't do it with arel.  I get the &quot;stack level too deep&quot; on the &quot;joined.to_sql&quot; line.</p>
  <pre><code>      members = Core::Member.arel_table
        jobs = Perf::Job.arel_table
        cool_relation = jobs.where(jobs[:state].not_in(%w[COMPLETETED RUNNING unknown]))
        relation = cool_relation.join( Arel::Nodes::SqlLiteral.new &lt;&lt;-SQL
                INNER JOIN core_members ON core_members.login = jobstat_jobs.login
        SQL
        ).join(Arel::Nodes::SqlLiteral.new &lt;&lt;-SQL
            RIGHT JOIN sessions_projects_in_sessions ON
            sessions_projects_in_sessions.project_id = core_members.project_id
          SQL
        ).group(members[:project_id]).project(members[:project_id].as('id'))
  
        hours = '(extract(epoch from (end_time - start_time))/ 3600)'
        selections = {
          node_hours: &quot;(sum((#{hours})*num_nodes))&quot;,
          jobs: &quot;count(jobstat_jobs.id)&quot;
        }
        selections.each do |key, value|
          relation = relation.project(
            Arel::Nodes::SqlLiteral.new(value).as(key.to_s)
          )
        end
        state_relation = relation.project(jobs[:state].as('state'))
                                 .group(jobs[:state])
        s = state_relation.as('s')
        pp ActiveRecord::Base.connection.exec_query(state_relation.to_sql).to_a
        joined = relation.join(s)
                         .on(jobs[:id].eq(s[:id]))
                         .project(s[:id], s[:state])
        puts joined.to_sql
        joined
  </code></pre>
  <p>I noticed the strange thing. When I replace &quot;joined = relation&quot; with &quot;jobs.where(jobs[:state].not_in(%w[COMPLETETED RUNNING unknown]))&quot; it works. But when I replace &quot;joined = relation&quot; with &quot;joined = cool_relation&quot; it doesn't work and I get &quot;stack level too deep&quot; (these 2 replacements are almost the same).</p>
  <p>Arel v 9.0.0, Postgresql</p>