On Tue, Feb 20, 2024 at 2:11 PM Konstantin Dzreev <[email protected]>
wrote:

> Hi guys.
>
> I have a postgresql database with multiple schemas (namespaces).
> Is there a way to use namespaces with ORM models? I did not find an easy
> way to tell all my models what namespace they should switch to.
>
> ```ruby
> namespaces = [:customer1, :customer2, ...]
> namespaces.each do |ns|
> # Change datasets on all my models
> Product.set_dataset(Sequel[ns][Product.table_name])
> User.set_dataset(Sequel[ns][User.table_name])
> # etc...
> # do more things here
> end
> ```
>
> The example above seems to work, but I don't like it. It is not thread
> safe, it changes the namespaces globally.
> I can make it safer by creating an ephemeral namespaced model:
>
> ```ruby
> def with_namespace(model, namespace, &block)
> model_with_namespace = Class.new(model)
> model_with_namespace.set_dataset(Sequel[namespace.to_sym][model.table_name
> ]
> block.call(model_with_namespace)
> end
>
> with_namespace(Product, :customer1) do |product|
> data = product.all
> # do more things here
> end
> ```
> but it is still per model, and it pollutes memory.
>
> Having something like an example below would really help:
>
> ```ruby
> DB.with_namespace(:customer1) do
> # all models are automatically namespaced inside the block
> data = Product.all
> # do more things here
> end
> ```
>
> Is there anything like this already, or am I not using the namespaces
> properly?
> Thank you!
>

You could use a delayed evaluation for the table name:

DB.singleton_class.send(:attr_reader, :current_namespace)

def DB.with_namespace(namespace)
  ns = @current_namespace
  @current_namespace = namespace
  yield
ensure
  @current_namespace = ns
end

Product.set_dataset DB.from(Sequel.delay{Sequel[DB.current_namespace ||
:public][:products]})

Thanks,
Jeremy

-- 
You received this message because you are subscribed to the Google Groups 
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/sequel-talk/CADGZSSeii0yPZd%2Br8ZjV3m0Z5XebFA3d9Hd7n43JdOuCMqS8mQ%40mail.gmail.com.

Reply via email to