Does Sequel::Model offer column aliases

13 views
Skip to first unread message

Leo Arnold

unread,
Jul 23, 2021, 7:33:00 AMJul 23
to sequel-talk
Hi there,

I am using Sequel to access database tables with cryptic column names and for the sake of my own sanity I would like to do something like

```
class ShoppingCart < Sequel::Model(:shopping_carts)
  column :krptk89, as: :campaign_id
end

ShoppingCart.where(campaign_id: 3).sql
# Expected: SELECT * FROM shopping_carts WHERE krptk89 = 3;
```

Does Sequel offer something like that?

Thanks

Leo

Leo Arnold

unread,
Jul 23, 2021, 7:58:29 AMJul 23
to sequel-talk
I realize there is the option

```
class ShoppingCart < Sequel::Model(:shopping_carts)
  dataset_module do
    def with_campaign_id(campaign_id)
      where(krptk89: campaign_id)
    end
  end
end
```

but I was also hoping for

```
shopping_cart.campaign_id = 5
shopping_cart.save
# Expected: UPDATE shopping_carts SET campaign_id = 5 WHERE ID = 123;
```

Also, there is no such thing as a "campaigns table", so I cannot use associations in my real world use case.

Jeremy Evans

unread,
Jul 23, 2021, 1:33:06 PMJul 23
to seque...@googlegroups.com
Sequel offers column aliases at the model level:

class ShoppingCart < Sequel::Model(:shopping_carts)
  def_column_alias(:campaign_id, :krptk89)
end

sc = ShoppingCart.new(:campaign_id=>3)
sc.krptk89 # => 3

However, this doesn't extend to the dataset level as in your example.  You can use custom dataset methods, as you showed in the later email.  You can also override Dataset#input_identifier:

SHOPPING_CART_MAPPING = {"campaign_id"=>'krptk89'}
ds = DB[:shopping_carts].with_extend do
  def input_identifier(v)
    SHOPPING_CART_MAPPING[v] || super
  end
end
class ShoppingCart < Sequel::Model(ds)
  def_column_alias(:campaign_id, :krptk89)
end

ShoppingCart.where(campaign_id: 3).sql
"SELECT * FROM `shopping_carts` WHERE (`krptk89` = 3)"

Thanks,
Jeremy
Reply all
Reply to author
Forward
0 new messages