16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
|
# File 'lib/cli/commands/new_app/files/db_rake.rb', line 16
def self.content(app_name, db_name)
" # typed: false\n\n # run on the database server once:\n #\n # CREATE DATABASE \#{db_name}_${environment};\n\n require 'zeitwerk/inflector'\n require_relative \"../../app\"\n\n namespace :db do\n # RACK_ENV=development bundle exec rake db:create\n desc \"Create the database\"\n task :create do\n envs = ENV.key?(\"RACK_ENV\") ? [ENV.fetch(\"RACK_ENV\")] : %w[development test]\n envs.each do |env|\n ENV[\"RACK_ENV\"] = env\n db_name = \"\#{db_name}_\\\#{env}\"\n puts(\"Creating database \\\#{db_name}...\")\n\n reset_memoized_class_level_instance_vars(\#{app_name})\n url = \#{app_name}.default_db_url.dup # frozen string\n url.gsub!(db_name, \"postgres\")\n puts(\"Connecting to \\\#{url.gsub(%r{://.*@}, \"_REDACTED_\")}\")\n db = Sequel.connect(url)\n\n begin\n db.execute(\"CREATE DATABASE \\\#{db_name}\")\n puts(\"Created database \\\#{db_name}.\")\n rescue Sequel::DatabaseError, PG::DuplicateDatabase\n puts(\"Database \\\#{db_name} already exists, skipping.\")\n end\n end\n end\n\n desc \"Drop the database\"\n task :drop do\n envs = ENV.key?(\"RACK_ENV\") ? [ENV.fetch(\"RACK_ENV\")] : %w[development test]\n envs.each do |env|\n ENV[\"RACK_ENV\"] = env\n db_name = \"\#{db_name}_\\\#{env}\"\n puts(\"Dropping database \\\#{db_name}...\")\n\n reset_memoized_class_level_instance_vars(\#{app_name})\n url = \#{app_name}.default_db_url.dup # frozen string\n url.gsub!(db_name, \"postgres\")\n puts(\"Connecting to \\\#{url.gsub(%r{://.*@}, \"_REDACTED_\")}\")\n db = Sequel.connect(url)\n\n begin\n db.execute(\"DROP DATABASE \\\#{db_name} (FORCE)\")\n puts(\"Dropped database \\\#{db_name}.\")\n rescue Sequel::DatabaseError, PG::DuplicateDatabase\n puts(\"Database \\\#{db_name} does not exists, nothing to drop.\")\n end\n end\n end\n\n desc \"Run migrations\"\n task :migrate do\n Sequel.extension(:migration)\n envs = ENV.key?(\"RACK_ENV\") ? [ENV.fetch(\"RACK_ENV\")] : %w[development test]\n envs.each do |env|\n ENV[\"RACK_ENV\"] = env\n db_name = \"\#{db_name}_\\\#{env}\"\n reset_memoized_class_level_instance_vars(\#{app_name})\n db = Sequel.connect(\#{app_name}.default_db_url)\n Sequel::Migrator.run(db, File.join(\#{app_name}.root, \"db/migrate\"))\n current_version = db[:schema_migrations].order(:filename).last[:filename].to_i\n puts \"Migrated \\\#{db_name} to version \\\#{current_version}!\"\n end\n\n Rake::Task[\"db:annotate\"].invoke\n end\n\n desc \"Rollback the last migration\"\n task :rollback do\n envs = ENV.key?(\"RACK_ENV\") ? [ENV.fetch(\"RACK_ENV\")] : %w[development test]\n Sequel.extension(:migration)\n envs.each do |env|\n ENV[\"RACK_ENV\"] = env\n db_name = \"\#{db_name}_\\\#{env}\"\n reset_memoized_class_level_instance_vars(\#{app_name})\n db = Sequel.connect(\#{app_name}.default_db_url)\n\n steps = (ENV[\"STEPS\"] || 1).to_i + 1\n versions = db[:schema_migrations].order(:filename).all\n\n if versions[-steps].nil?\n puts \"No more migrations to rollback\"\n else\n target_version = versions[-steps][:filename].to_i\n\n Sequel::Migrator.run(db, File.join(\#{app_name}.root, \"db/migrate\"), target: target_version)\n puts \"Rolled back \\\#{db_name} \\\#{steps} steps to version \\\#{target_version}\"\n end\n end\n end\n\n desc \"Seed the database\"\n task :seed do\n load File.join(\#{app_name}.root, \"db/seeds.rb\")\n end\n\n desc \"Generate a new migration file\"\n task :migration, [:name] do |_t, args|\n require \"fileutils\"\n require \"time\"\n\n # Ensure the migrations directory exists\n migrations_dir = File.join(\#{app_name}.root, \"db/migrate\")\n FileUtils.mkdir_p(migrations_dir)\n\n # Generate the migration number\n migration_number = Time.now.utc.strftime(\"%Y%m%d%H%M%S\")\n\n # Sanitize and format the migration name\n formatted_name = args[:name].to_s.gsub(/([a-z])([A-Z])/, '\\\\1_\\\\2').downcase\n\n # Combine them to create the filename\n filename = \"\\\#{migration_number}_\\\#{formatted_name}.rb\"\n file_path = File.join(migrations_dir, filename)\n\n # Define the content of the migration file\n content = <<~MIGRATION\n # typed: false\n # frozen_string_literal: true\n\n Sequel.migration do\n up do\n # your code here\n end\n\n down do\n # your code here\n end\n end\n MIGRATION\n\n # Write the migration file\n File.write(file_path, content)\n\n puts \"Generated migration: db/migrate/\\\#{filename}\"\n end\n\n desc \"Write the table schema to each model file, or a single file if filename (without extension) is provided\"\n task :annotate, [:model_file_name] do |_t, args|\n require \"fileutils\"\n\n db = \#{app_name}.raw_db_connection\n model_file_name = args[:model_file_name]&.to_s\n\n app_root_dir = TestApp.root\n app_dir = File.join(TestApp.root, \"app\")\n\n Dir.glob(\"app/**/*.rb\").each do |model_file|\n next if !model_file_name.nil? && model_file == model_file_name\n\n model_path = File.expand_path(model_file, app_root_dir)\n\n full_path = File.expand_path(model_file, app_root_dir)\n klass_constant_name = APP_LOADER.inflector.camelize(File.basename(model_file, \".rb\"), full_path)\n\n #\n # root namespaces in Zeitwerk are flattend, e.g. if \"app/models\" is a root namespace\n # then a file \"app/models/airport.rb\" is loaded as \"::Airport\".\n # if it weren't a root namespace, it would be \"::Models::Airport\".\n #\n root_dir_namespaces = APP_LOADER.dirs.filter_map { |dir| dir == app_dir ? nil : Pathname.new(dir).relative_path_from(Pathname.new(app_dir)).to_s }\n relative_path = Pathname.new(full_path).relative_path_from(Pathname.new(app_dir)).to_s\n root_dir_of_model = root_dir_namespaces.find { |root_dir| relative_path.start_with?(root_dir) }\n relative_path.sub!(\"\\\#{root_dir_of_model}/\", \"\") unless root_dir_of_model.nil? || root_dir_of_model.empty?\n\n namespace_parts = relative_path.split(\"/\")\n namespace_parts.pop\n namespace_parts.map! { |part| APP_LOADER.inflector.camelize(part, full_path) }\n\n constant_name = \"\\\#{namespace_parts.join('::')}::\\\#{klass_constant_name}\"\n\n model_klass = Object.const_get(constant_name)\n next unless model_klass.respond_to?(:table_name)\n\n table_name = model_klass.table_name\n schema = db.schema(table_name)\n\n schema_comments = format_schema_comments(table_name, schema)\n file_content = File.read(model_path)\n\n file_content_without_schema_info = file_content.sub(/# == Schema Info\\\\n(.*?)(\\\\n#\\\\n)?\\\\n(?=\\\\s*(?:class|module))/m, \"\")\n\n # Insert the new schema comments before the module/class definition\n first_module = namespace_parts.first\n first_module_or_class = first_module.nil? ? \"class \\\#{klass_constant_name}\" : \"module \\\#{first_module}\"\n modified_content = file_content_without_schema_info.sub(/(A|\\\\n)(\\\#{first_module_or_class})/m, \"\\\\\\\\1\\\#{schema_comments}\\\\n\\\\n\\\\\\\\2\")\n\n File.write(model_path, modified_content)\n end\n end\n end\n\n def reset_memoized_class_level_instance_vars(app)\n %i[\n @default_db_name\n @default_db_url\n @raw_db_connection\n ].each do |ivar|\n app.remove_instance_variable(ivar) if app.instance_variable_defined?(ivar)\n end\n end\n\n def format_schema_comments(table_name, schema)\n lines = [\"# == Schema Info\", \"#\", \"# Table name: \\\#{table_name}\", \"#\"]\n schema.each do |column|\n name, info = column\n type = \"\\\#{info[:db_type]}(\\\#{info[:max_length]})\" if info[:max_length]\n type ||= info[:db_type]\n type = \"\\\#{type}, \" if type.size >= 20 \\# e.g. \"timestamp without time zone\" exceeds 20 characters\n null = info[:allow_null] ? 'null' : 'not null'\n primary_key = info[:primary_key] ? ', primary key' : ''\n lines << \"# \\\#{name.to_s.ljust(20)}:\\\#{type.to_s.ljust(20)}\\\#{null}\\\#{primary_key}\"\n end\n lines.join(\"\\\\n\") + \"\\\\n#\"\n end\n\n RUBY\nend\n"
|