Skip to content

Instantly share code, notes, and snippets.

@wilsonsilva
Created December 23, 2024 12:42
Show Gist options
  • Save wilsonsilva/fbb7f88804cded3d6d62e1fc5ad3d18d to your computer and use it in GitHub Desktop.
Save wilsonsilva/fbb7f88804cded3d6d62e1fc5ad3d18d to your computer and use it in GitHub Desktop.
Creating a new sqlite db on the fly when a new account gets created
# Source https://x.com/benigartenmann/status/1871117811072065877
class Account < GlobalRecord
after_create_commit :create_shard
private
def create_shard
yaml_config = YAML.load_file("config/database.yml", aliases: true)
root_db_config = ActiveRecord::Base.connection_db_config.configuration_hash.deep_dup.freeze
tenant_shard_config = root_db_config.merge(
database: "storage/#{self.subdomain}.sqlite3",
migrations_paths: "db/migrate"
)
yaml_config[Rails.env][self.subdomain] = JSON.parse(tenant_shard_config.to_json)
File.open("config/database.yml", "w") do |f|
YAML.dump(yaml_config, f)
end
db_config = ActiveRecord::DatabaseConfigurations::HashConfig.new(
Rails.env,
self.subdomain,
tenant_shard_config
)
ActiveRecord::Base.configurations.configurations << db_config
connected_shards = yaml_config[Rails.env].keys.each_with_object({}) do |shard, shards|
sym_shard = shard.to_sym
shards[sym_shard] = {
writing: sym_shard,
reading: sym_shard
}
end
ApplicationRecord.connects_to(shards: connected_shards)
ActiveRecord::Tasks::DatabaseTasks.with_temporary_connection(db_config) do
ActiveRecord::Tasks::DatabaseTasks.migrate
if ActiveRecord.dump_schema_after_migration
schema_format = ENV.fetch("SCHEMA_FORMAT", ActiveRecord.schema_format).to_sym
ActiveRecord::Tasks::DatabaseTasks.dump_schema(
db_config,
schema_format
)
end
end
end
end
@wilsonsilva
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment