Reputation: 452
I am trying to create a rails application that can create database tables in a non-primary DB, given a json schema. The app is intended to act as an interface to manage a secondary database. The dynamically created tables will never be accessed by the app except probably (very rarely) to alter the tables.
Here is my setup
config
|
|- secondary_db.yml
|- initializers/secondary_db.rb
So now my secondary DB config is available throughout the app.
I have a model called Topic
which accepts an attribute topic_schema
of type json. Assume that the schema is shallow with no hierarchy or nesting.
topic_schema: {
"type" => "object",
"required" => ["a", "b"],
"properties" => {
"a" => {"type" => "integer"},
"b" => {"type" => "string"}
}
}
I have to create a service class called TableCreator that can take this json schema and create a table based on it. So every time I create a new Topic
with a valid json topic_schema
, the table gets created automatically. Remember my app is never going to read or write from this table, rarely I may have to alter or delete this table. So I do not need to keep track of these tables in my schema.rb file
I can create a service that can convert json schema to table migration. I want to figure out how can I run the migration to my secondary_db without altering the schema file of my application. Thanks a lot for any help :)
Upvotes: 0
Views: 458
Reputation: 452
Here is TableCreator class that achieved what I wanted to do.
class TableCreator < ActiveRecord::Migration[6.0]
def create
with_secondary_db_connection do
create_table :ts_test_table, id: false do |t|
t.datetime 'time'
t.string 'value'
end
end
end
def with_secondary_db_connection
primary = ActiveRecord::Base.remove_connection
ActiveRecord::Base.establish_connection(TIMESCALE_CONFIG)
yield
ensure
ActiveRecord::Base.establish_connection(primary)
end
end
Thanks Max for the suggestion
Upvotes: 2