Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add example of using a CTE #295

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions source/5.0/learn/sql/queries.html.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,47 @@ class Users < ROM::Relation[:sql]
end
```

## Using Common Table Expressions in a Relation

Since you can use `Relation#new(dataset)` to create a relation using a Sequel
dataset which uses a CTE. The only caveat is that _you_ are responsible for
ensuring that the resulting schema is compatible with the current one (as in,
the one which is defined in the relation object that you use).

For more information, [see this forum question](https://discourse.rom-rb.org/t/custom-query-i-e-with-recursive/298/2).

```ruby
module Authentication
module Relations
class Accounts < ROM::Relation[:sql]
schema :accounts, infer: false do
attribute :id, Types::Int
attribute :name, Types::String
attribute :status_id, Types::ForeignKey(:account_statuses)
end

def verified_admin_accounts
admin_accounts_cte = db[:accounts].with(:accounts, db[:accounts].where(admin: true))
conditions = { db[:account_statuses][:name] => 'Verified' }
ds = admin.join(:account_statuses, id: :status_id, conditions)

# Create the relation using our own custom dataset.
#
# Note: We must ensure that the dataset schema matches the relation
# schema so ROM can perform the proper mappings.
new(ds.select(qualified_columns))
end

private

def db
dataset.db
end
end
end
end
```

## Learn more

Check out API documentation:
Expand Down