Forked from wilsonsilva/one-sqlite-db-per-account.rb
Created
December 23, 2024 15:28
-
-
Save 7urkm3n/5c7f7aa1ffede2559cfa01ca8d69224f to your computer and use it in GitHub Desktop.
Creating a new sqlite db on the fly when a new account gets created
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Author
7urkm3n
commented
Dec 23, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment