graphql-ruby icon indicating copy to clipboard operation
graphql-ruby copied to clipboard

[PRO] StableRelationConnection reports invalid cursor when underlying table name conflicts with a SQL keyword

Open jtrull opened this issue 3 years ago • 6 comments

Describe the bug

Similar to #4485 (and I'm sorry that I failed to notice and mention this then), GraphQL::Pro::StableRelationConnection does not quote table and column names when generating the WHERE conditions for pagination. It looks like the code responsible for this is actually in lib/graphql/pro/relation_connection/condition.rb.

Like #4485, if you (foolishly) have table or column names that are also SQL keywords, invalid SQL will be generated.

In my case, the application uses singular table names and has a table named order. When generating the query for a paginated Order ConnectionType, StableRelationConnection generates SQL like:

SELECT "order".*, "order"."id" AS cursor_0 FROM "order" WHERE (order.id > 1) ORDER BY "order"."id" asc LIMIT $1

Note the lack of quotes around "order" in the WHERE clause.

Executing the query raises ActiveRecord::StatementInvalid which is then reraised as GraphQL::Pro::StableRelationConnection::InvalidCursorError. Of course, in this case, there is nothing actually wrong with the cursor value.

Versions

graphql version: 2.0.22 graphql-pro version: 1.24.6 rails version: 7.0.5

Steps to reproduce

# frozen_string_literal: true

class CreateReproTables < ActiveRecord::Migration[7.0]
  def change
    create_table :order do |t|
      t.integer :amount_cents, null: false
    end
  end
end

CreateReproTables.migrate(:up)

class Order < ActiveRecord::Base
  self.table_name = 'order'
end

3.times { |i| Order.create!(amount_cents: 100 * i) }

module Types; end

class Types::Order < GraphQL::Schema::Object
  field :amount_cents, Int, null: false 
end

class Types::QueryType < GraphQL::Schema::Object
  field :orders, Types::Order.connection_type, null: false
  
  def orders
    ::Order.all
  end
end

class ReproSchema < GraphQL::Schema
  query Types::QueryType
  connections.add(
    ActiveRecord::Relation, GraphQL::Pro::PostgresStableRelationConnection
  )
end

QUERY = <<~GRAPHQL
  query Orders($after: String) {
    orders(first: 1, after: $after) {
      nodes { amountCents }
      pageInfo { endCursor hasNextPage }
    }
  }
GRAPHQL

after = nil

loop do
  result = ReproSchema.execute(QUERY, variables: { after: })
  if result['errors']
    pp result
    break 
  end

  puts result.dig('data', 'orders', 'nodes', 0, 'amountCents')
  after = result.dig('data', 'orders', 'pageInfo', 'endCursor')
  break unless result.dig('data', 'orders', 'pageInfo', 'hasNextPage')
end

Expected behavior

Outputs:

0
100
200

Actual behavior

Outputs:

0
#<GraphQL::Query::Result @query=... @to_h={"data"=>{"orders"=>{"nodes"=>nil, "pageInfo"=>{"endCursor"=>nil, "hasNextPage"=>false}}}, "errors"=>[{"message"=>"Invalid cursor for `after: \"WzFd\"`. Fetch a new cursor and try again.", "locations"=>[{"line"=>3, "column"=>5}], "path"=>["orders", "nodes"]}]}>

jtrull avatar Jun 07 '23 21:06 jtrull

Thanks for the detailed report and sorry I missed this spot when fixing #4485! I'll get a patch ready soon and follow up here.

rmosolgo avatar Jun 08 '23 01:06 rmosolgo

Hey, I just released graphql-pro v1.24.7 which includes proper quoting in WHERE clauses. Please give it a try and let me know how it goes for you! Thanks again for reporting this issue.

rmosolgo avatar Jun 16 '23 20:06 rmosolgo

Looks good to me! Had a (no longer) failing test locked and loaded. Thanks much and have a great weekend!

jtrull avatar Jun 16 '23 21:06 jtrull

@rmosolgo I have the same issue when using table aliases. They are quoted automatically but it turns out "T" != T when dealing with table aliases.

The workaround is to use "T" in my code but it's still a bit painful and dangerous

Query example (after invalid quoting of "T"."ordering"):

SELECT users.*,
       T.slug AS subscription_slug,
       "T"."ordering" AS cursor_0,
       "users"."followers_count" AS cursor_1,
       "users"."id" AS cursor_2
FROM "users"
LEFT OUTER JOIN
  (SELECT subscriptions.*,
          U.followers_count AS ordering
   FROM "subscriptions"
   INNER JOIN users U ON subscriptions.subscribable_id = U.id
   WHERE "subscriptions"."subscriber_id" = '20db9a8f-e6fb-436a-848b-ee8126a781b2'
     AND "subscriptions"."subscribable_type" = 'User') T ON users.id = T.subscribable_id
WHERE "users"."id" IN
    (SELECT "users"."id"
     FROM "users"
     INNER JOIN "subscriptions" ON "users"."id" = "subscriptions"."subscriber_id"
     WHERE "subscriptions"."subscribable_id" = '20db9a8f-e6fb-436a-848b-ee8126a781b2'
       AND "subscriptions"."subscribable_type" = 'User')
ORDER BY T.ordering DESC NULLS LAST,
                         users.followers_count DESC,
                         "users"."id" ASC
LIMIT 51

such avatar Feb 20 '24 15:02 such

Hey, thanks for reporting that. It looks like GraphQL-Pro should use unquoted T in that case. I bet I can make it detect an unquoted reference in ORDER BY and use that verbatim. I'll take a look soon and follow up back here :+1:

rmosolgo avatar Feb 20 '24 20:02 rmosolgo

I just released a fix for this in GraphQL-Pro v1.26.4. Now, it checks to see if table or column names were quoted in the original SQL, and if they weren't, then it doesn't apply quotes of its own in the cursor_... selects.

If anyone encounters more trouble with that, please open a new issue or get in touch by email!

rmosolgo avatar Feb 27 '24 20:02 rmosolgo