5 Commits

Author SHA1 Message Date
cryptogopher cb09a30ef1 Remove unused migration strategy code 2026-11-26 02:37:46 +01:00
cryptogopher b6d2c19b0b Auto-create check constraints for text fields with limit
Move column defaults from migration strategy to migrations.
Compact index creation inside migrations.
Disable database schema generation.
2026-11-26 02:32:09 +01:00
cryptogopher 74f9a09098 Add Tag 2026-11-25 23:24:50 +01:00
cryptogopher 978217b3be Discontinue MySQL support
This is intended to reduce development effort. Support may be
reintroduced later, if justified.
2026-11-25 23:24:50 +01:00
cryptogopher 821ffb3551 Shorten core extensions module names 2026-11-18 23:04:55 +01:00
50 changed files with 637 additions and 492 deletions
+5 -2
View File
@@ -15,8 +15,10 @@
/config/master.key
/config/puma.rb
# Ignore test database.
/db/test.sqlite3
# Ignore database files.
/db/*.sqlite3
/db/*.sqlite3-shm
/db/*.sqlite3-wal
# Ignore all logfiles and tempfiles.
/log/*
@@ -46,5 +48,6 @@
/.vim
/.viminfo
/.webdrivers
/.wget-hsts
*.swp
Session.vim
+18
View File
@@ -4,6 +4,17 @@ DESIGN
Below is a list of design decisions. The justification is to be consulted
whenever a change is considered, to avoid regressions.
### Database engine support
* currently, only SQLite is supported; the reasons for not supporting other
engines under consideration are outlined below:
* MariaDB:
* lack of support for Common Table Expressions (CTEs) in UPDATE and
DELETE statements (https://jira.mariadb.org/browse/MDEV-18511),
* MySQL:
* lack of support for the ORDER BY clause within recursive CTEs - which
makes it difficult to sort hierarchies using a depth-first approach.
### Data type for DB storage of numeric values (`decimal` vs `float`)
* among database engines supported (by Rails), SQLite offers storage of
@@ -74,3 +85,10 @@ whenever a change is considered, to avoid regressions.
* assuming that user input with _precision > DIG_ is as rare as in
the range _(0, MIN)_, the decision is to choose input which requires
the least/simplest additional code.
### Other
* Arel usage inside models should be avoided in favor of direct query fragments.
They have similar portability and are much more readable. Anything more
complex, e.g. named functions not available in Rails should be extracted into
extensions.
+5 -17
View File
@@ -5,21 +5,9 @@ gem "rails", "~> 8.1.4"
gem "sprockets-rails"
gem "puma", "~> 6.0"
gem "sassc-rails"
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem.
gem "tzinfo-data", platforms: %i[ mingw mswin x64_mingw jruby ]
# TODO: select db gems automatically?
# database_config = ERB.new(File.read("config/database.yml")).result
# YAML.load(database_config, aliases: true).values.map { |env| env["adapter"] }.uniq
group :mysql, optional: true do
gem "mysql2", "~> 0.5"
end
group :postgresql, optional: true do
gem "pg", "~> 1.5"
end
group :sqlite, optional: true do
gem "sqlite3", "~> 2.7"
end
gem "sqlite3", "~> 2.7"
gem "devise", "~> 5.0.4"
@@ -31,15 +19,15 @@ group :development, :test do
end
group :development do
# Use console on exceptions pages [https://github.com/rails/web-console]
# Use console on exceptions pages [https://github.com/rails/web-console].
gem "web-console"
# Add speed badges [https://github.com/MiniProfiler/rack-mini-profiler]
# Add speed badges [https://github.com/MiniProfiler/rack-mini-profiler].
# gem "rack-mini-profiler"
end
group :test do
# Use system testing [https://guides.rubyonrails.org/testing.html#system-testing]
# Use system testing [https://guides.rubyonrails.org/testing.html#system-testing].
# TODO: move back from git after this PR is included:
# https://github.com/teamcapybara/capybara/pull/2862
gem "capybara", git: "https://github.com/teamcapybara/capybara", branch: "table_row-optional-header-and-integer-locator"
-11
View File
@@ -157,8 +157,6 @@ GEM
minitest (6.0.6)
drb (~> 2.0)
prism (~> 1.5)
mysql2 (0.5.7)
bigdecimal
net-imap (0.6.7)
date
net-protocol
@@ -186,13 +184,6 @@ GEM
nokogiri (1.19.4-x86_64-linux-musl)
racc (~> 1.4)
orm_adapter (0.5.0)
pg (1.7.0)
pg (1.7.0-aarch64-linux)
pg (1.7.0-aarch64-linux-musl)
pg (1.7.0-arm64-darwin)
pg (1.7.0-x86_64-darwin)
pg (1.7.0-x86_64-linux)
pg (1.7.0-x86_64-linux-musl)
pp (0.6.4)
prettyprint
prettyprint (0.2.0)
@@ -328,8 +319,6 @@ DEPENDENCIES
devise (~> 5.0.4)
i18n!
importmap-rails
mysql2 (~> 0.5)
pg (~> 1.5)
puma (~> 6.0)
rails (~> 8.1.4)
sassc-rails
+5 -44
View File
@@ -16,10 +16,6 @@ environment, see the _Contributing_ section below.
* Server side:
* Ruby interpreter, depending on the version of Rails used (see _Gemfile_),
* https://guides.rubyonrails.org/upgrading_ruby_on_rails.html#ruby-versions
* database (e.g. SQLite, MySQL >= 8.0) supporting:
* recursive Common Table Expressions (CTE) for SELECT/UPDATE/DELETE,
* MariaDB does not support CTE for UPDATE/DELETE
(https://jira.mariadb.org/browse/MDEV-18511)
* for testing: browser as specified in _Client side_ requirements
* Client side:
* browser (e.g. Firefox >= 121) supporting:
@@ -30,20 +26,14 @@ environment, see the _Contributing_ section below.
### Gems
On systems where development tools and libraries are not installed by default
(such as Ubuntu), you should install them before proceeding with Ruby gems.
Select the database client library according to the database engine you are
planning to use:
(such as Ubuntu), you should install them before proceeding with Ruby gems:
sudo apt install build-essential libyaml-dev libmysqlclient-dev
sudo apt install build-essential libyaml-dev
git clone https://gitea.michalczyk.pro/fixin.me/fixin.me.git
cd fixin.me
bundle config --local frozen true
bundle config --local path .gem
Select which database engine gem to install (mysql, postgresql, sqlite):
bundle config --local with mysql
bundle install
### Configuration
@@ -64,13 +54,6 @@ Precompile assets:
### Database
Grant database user and privileges:
> mysql -p
mysql> create user fixinme@localhost identified by 'Some-password1%';
mysql> grant all privileges on fixinme.* to fixinme@localhost;
mysql> flush privileges;
Copy config template and update database configuration:
cp -a config/database.yml.dist config/database.yml
@@ -115,10 +98,9 @@ Contributing
### Gems
Install development and testing gems, including at least MySQL and SQLite
database adapters:
Install development and testing gems:
bundle config --local with development test mysql sqlite
bundle config --local with development test
#### Using gems from local git repos
@@ -147,18 +129,9 @@ assets.
### Database
Grant database user privileges for development and test environments. Example
below shows how to grant privileges to all databases which names start with
`fixinme-` on MySQL:
> mysql -p
mysql> create user `fixinme-dev`@localhost identified by '<some password>';
mysql> grant all privileges on `fixinme-%`.* to `fixinme-dev`@localhost;
mysql> flush privileges;
Dumping development data before database reset:
mysqldump -h <address> -u <user> -p --no-create-info --no-tablespaces --complete-insert <database> > tmp/data.sql
TODO
### Development environment
@@ -166,10 +139,6 @@ Starting application server in development environment:
bundle exec rails s -e development
Accessing database console when more than one test db is present:
bundle exec rails dbconsole -e test --db sqlite3
For running rake tasks, prepend command with environment:
RAILS_ENV=development bundle exec rails ...
@@ -190,14 +159,6 @@ Tests need to be run from within toplevel application directory:
bundle exec rails test test/system/users_test.rb --seed 1234
* system tests for selected database configuration (if multiple present):
bundle exec rails test:system --include /^test_sqlite3_/
* single system test for all database configurations (if multiple present):
bundle exec rails test:system --include /^test_\\w+_add_unit$/
### Icons
Pictogrammers Material Design Icons: https://pictogrammers.com/library/mdi/
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" id="icon" viewBox="0 0 24 24"><path d="M6.5 10C7.3 10 8 9.3 8 8.5S7.3 7 6.5 7 5 7.7 5 8.5 5.7 10 6.5 10M9 6L16 13L11 18L4 11V6H9M9 4H4C2.9 4 2 4.9 2 6V11C2 11.6 2.2 12.1 2.6 12.4L9.6 19.4C9.9 19.8 10.4 20 11 20S12.1 19.8 12.4 19.4L17.4 14.4C17.8 14 18 13.5 18 13C18 12.4 17.8 11.9 17.4 11.6L10.4 4.6C10.1 4.2 9.6 4 9 4M13.5 5.7L14.5 4.7L21.4 11.6C21.8 12 22 12.5 22 13S21.8 14.1 21.4 14.4L16 19.8L15 18.8L20.7 13L13.5 5.7Z" /></svg>

After

Width:  |  Height:  |  Size: 473 B

+64
View File
@@ -0,0 +1,64 @@
class TagsController < ApplicationController
before_action ->{ @tag = current_user.tags.find_by!(id: params[:id]) },
only: [:new, :edit, :update, :reposition, :destroy],
unless: ->{ action_name == "new" && params[:id].nil? }
before_action except: :index do
raise AccessForbidden unless current_user.at_least(:active)
end
def index
@tags = current_user.tags.ordered.includes(:supertag, :subtags)
end
def new
@tag = current_user.tags.new(supertag: @tag)
end
def create
@tag = current_user.tags.new(params.expect(Tag::ATTRIBUTES))
if @tag.save
@before = @tag.succeeding
@ancestors = @tag.ancestors
flash.now.notice = t('.success', tag: @tag)
else
render_errors @tag
end
end
def edit
end
def update
if @tag.update(params.except(:supertag_id).expect(Tag::ATTRIBUTES))
@ancestors = @tag.ancestors
flash.now.notice = t('.success', tag: @tag)
else
render_errors @tag
end
end
def reposition
tag_params = params.expect(tag: :supertag_id)
@prev_supertag_id = @tag.supertag_id
if @tag.update(tag_params)
@ancestors = Tag.ancestors([@prev_supertag_id, @tag.supertag_id])
.includes(:subtags)
@tags = @tag.with_progenies.includes(:subtags)
@before = @tag.succeeding(true)
else
# Until UI blocks all disallowed repositions, render error messages if present.
flash.now.alert = @tag.errors.full_messages
render :nothing
end
end
def destroy
@tag.destroy!
@ancestors = @tag.ancestors
flash.now.notice = t('.success', tag: @tag)
end
private
end
+3 -1
View File
@@ -161,8 +161,10 @@ module ApplicationHelper
menu_tabs = [
['measurements', 'scale-bathroom', :restricted],
['quantities', 'axis-arrow', :restricted, 'right'],
['tags', 'tag-multiple-outline', :restricted],
['units', 'weight-gram', :restricted],
# TODO: display users tab only if >1 user present; sole_user?/sole_admin?
# TODO: display users tab only if >1 user present; sole_user?/sole_admin?;
# change status field to proc?
['users', 'account-multiple-outline', :admin],
]
+113
View File
@@ -0,0 +1,113 @@
class Tag < ApplicationRecord
ATTRIBUTES = {tag: [:label, :description, :supertag_id]}
attr_cached :depth
belongs_to :user
belongs_to :supertag, optional: true, class_name: "Tag"
alias_method :parent, :supertag
has_many :subtags, ->{ order(:label) }, class_name: "Tag", inverse_of: :supertag,
# Database allows cascade deletion, this is application level safety net.
dependent: :restrict_with_error
#has_many :quantities, dependent: :restrict_with_error
# TODO: try to remove validations and replace them with db constraints.
# All :supertag checks may be performed on record instead of :supertag_id, as
# record is loaded anyway by presence validator.
# Disallow #blank? (i.e. non-nil, non-existent ID) record association.
# TODO: use version below after bug fixed, https://github.com/rails/rails/issues/59879
# validates :supertag, allow_nil: true, presence: true, comparison: {...}
validates :supertag, if: :supertag_id, presence: true,
# TODO: add check constraint
comparison: {other_than: :itself, message: :self_reference}
# TODO: add foreign key constraint tag.user == supertag.user
validates :user_id, if: :supertag_id,
comparison: {equal_to: ->(tag){ tag.supertag.user_id }, message: :user_mismatch}
validate on: :update, if: :supertag_changed? do
errors.add(:supertag, :descendant_reference) if ancestor_of?(supertag)
end
validates :label, presence: true, uniqueness: {scope: :user_id},
length: {maximum: type_for_attribute(:label).limit}
validates :description, length: {maximum: type_for_attribute(:description).limit}
after_initialize :update_depth, if: :new_record?
before_save :update_depth, if: :supertag_changed?
after_update if: :depth_previously_changed? do
Tag.with_recursive(updated: [
Tag.reselect(id: :tag_id).select(depth: :tag_depth).where(id: id),
Tag.reselect(:id, 'tag_depth + 1').joins('JOIN updated ON tag_id = supertag_id')
# JOIN could be replaced with 'FROM updated WHERE id = tag_id' if Rails
# supported UPDATE FROM, https://sqlite.org/lang_update.html#update_from
]).joins(:updated).update_all('depth = tag_depth')
end
def to_s
tag.pre label
end
def to_s_with_depth
# em space, U+2003
' ' * depth + label
end
def destroyable?
subtags.empty?
end
# TODO: move to ApplicationRecord?
default_scope { select(arel_table[Arel.star]) }
# Return: ordered [sub]hierarchy.
scope :ordered, ->(root: nil, include_root: true) {
Tag.with_recursive(ordered: [
where(root && include_root ? :id : :supertag_id => root),
Tag.joins('JOIN ordered ON tags.supertag_id = ordered.id')
.order(depth: :desc, label: :asc)
]).from('ordered AS tags')
}
# Return: ancestors of `leaf(s)`, inclusive.
scope :ancestors, ->(leafs) {
return none if leafs.nil?
Tag.with_recursive(ancestors: [
Tag.where(id: leafs),
Tag.joins('JOIN ancestors ON tags.id = ancestors.supertag_id')
]).from('ancestors AS tags')
}
# Return: succeeding record in order of appearance. Used for partial view reload.
def succeeding(subtree = false)
# Recursive SELECT cannot use window functions. WHERE is evaluated before
# window function in SELECT - requires use of subquery.
# This is more compact, but probably less efficient version. Also it doesn't
# support `subtree` option. May be freely removed, or replace longer version.
#Tag.from(user.tags.ordered.select.lag(:id), :tags).where(lag_id: id).take
Tag.from(
# NULL default causes children of self to be skipped (label comparison fails).
Tag.ancestors(id).select.lag(:label, default: subtree ? nil : ''), :left
).joins('
JOIN tags ON (left.id = tags.supertag_id AND left.lag_label < tags.label) OR
(left.supertag_id IS NULL AND tags.supertag_id IS NULL AND left.label < tags.label)
').order(depth: :desc, label: :asc).take
end
# Return: ancestors of (possibly destroyed) self.
def ancestors
Tag.ancestors(supertag_id).order(:depth)
end
def with_progenies
user.tags.ordered(root: id)
end
def ancestor_of?(progeny)
Tag.ancestors(progeny.respond_to?(:id) ? progeny.id : progeny).exists?(id)
end
private
def update_depth
self[:depth] = supertag&.depth&.succ || 0
end
end
+1
View File
@@ -15,6 +15,7 @@ class User < ApplicationRecord
has_many :readouts, dependent: :delete_all
accepts_nested_attributes_for :readouts
has_many :quantities, dependent: :delete_all
has_many :tags, dependent: :delete_all
has_many :units, dependent: :delete_all
validates :email, presence: true, uniqueness: true,
+15
View File
@@ -0,0 +1,15 @@
<%# locals: (record: Tag.new, **attrs) %>
<%= tabular_fields_for record, form: attrs.dig(:data, :form) do |form| %>
<%- tag.tr class: "form", onkeydown: "formProcessKey(event)", **attrs do %>
<td style="--depth:<%= form.object.depth %>">
<%= form.text_field :label, autofocus: true, class: 'hstretch', required: true %>
<td><%= form.text_area :description, class: 'hstretch', escape: false, rows: 1 %>
<td><%= form.button %>
<td>
<%= image_link_to t(:discard), "close-outline", tags_path, class: 'dangerous',
name: :discard, onclick: render_turbo_stream('form_close', {id: attrs[:id]}) %>
<td><!-- TODO: add aria-disabled drag handle with proper vertical alignment? -->
<% end %>
<% end %>
+2
View File
@@ -0,0 +1,2 @@
<%= turbo_stream.close_form id %>
<%= turbo_stream.update :flashes %>
+24
View File
@@ -0,0 +1,24 @@
<tr id="<%= dom_target(tag) %>"
ondragstart="dragStart(event)" ondragend="dragEnd(event)"
ondragover="dragOver(event)" ondrop="drop(event)"
ondragenter="dragEnter(event)" ondragleave="dragLeave(event)"
data-drag-path="<%= reposition_tag_path(tag) %>"
data-drop-id="<%= dom_target(tag) %>"
data-drop-id-param="<%= field_name(:tag, :supertag_id) %>">
<td style="--depth:<%= tag.depth %>">
<%= link_to tag, edit_tag_path(tag), class: 'link', onclick: 'this.blur();',
data: {turbo_stream: true} %>
<td><%= tag.description %>
<% if current_user.at_least(:active) %>
<td>
<%= image_link_to t('.new_subtag'), 'plus-outline', new_tag_path(tag),
id: dom_target(:new, tag, :link), onclick: 'this.blur();',
data: {turbo_stream: true} %>
<td>
<%= image_button_to_if tag.destroyable?, t('.destroy'), 'delete-outline',
tag_path(tag), method: :delete %>
<td class="handle" draggable="true">&#x283F
<% end %>
+5
View File
@@ -0,0 +1,5 @@
<%= turbo_stream.close_form dom_target(:new, @tag.supertag || :tag) %>
<% @ancestors.each do |ancestor| %>
<%= turbo_stream.replace ancestor %>
<% end %>
<%= turbo_stream.before @before || :endmark, @tag %>
+4
View File
@@ -0,0 +1,4 @@
<% @ancestors.each do |ancestor| %>
<%= turbo_stream.replace ancestor %>
<% end %>
<%= turbo_stream.remove @tag %>
+13
View File
@@ -0,0 +1,13 @@
<% attrs = {record: @tag,
id: dom_target(:edit, @tag),
data: {form: dom_target(:edit, @tag, :form),
hidden_row: dom_target(@tag),
link: nil}} %>
<%= turbo_stream.append_all 'body' do %>
<%- tabular_form_with model: @tag, html: {id: attrs[:data][:form]} do %>
<% end %>
<% end %>
<%= turbo_stream.hide attrs[:data][:hidden_row] %>
<%= turbo_stream.after @tag, partial: 'form', locals: attrs -%>
+35
View File
@@ -0,0 +1,35 @@
<div class="rightside-area buttongrid">
<% if current_user.at_least(:active) %>
<%= image_link_to t('.new_tag'), 'plus-outline', new_tag_path, id: :new_tag_link,
onclick: 'this.blur();', data: {turbo_stream: true} %>
<% end %>
<%#= image_link_to t('.import_tags'), 'download-outline', default_tags_path,
class: 'tools-area' %>
</div>
<table class="main-area items-table">
<caption class="hint"><%= t '.no_items' %></caption>
<tbody>
<tr>
<th class="hmintext"><%= Tag.human_attribute_name(:label) %>
<th class="hexpand"><%= Tag.human_attribute_name(:description) %>
<% if current_user.at_least(:active) %>
<th colspan="3"><%= t :actions %>
<tr id="tag_" hidden
ondragover="dragOver(event)" ondrop="drop(event)"
ondragenter="dragEnter(event)" ondragleave="dragLeave(event)"
data-drop-id="tag_" data-drop-id-param="<%= field_name(:tag, :supertag_id) %>">
<th colspan="5"><%= t '.top_level_drop' %>
<% end %>
<%= render @tags %>
<% if current_user.at_least(:active) %>
<tr id="endmark" hidden>
<tfoot>
<%= render partial: 'form', locals: {hidden: true} %>
<% end %>
</table>
+16
View File
@@ -0,0 +1,16 @@
<% target_id = dom_target(:new, @tag.supertag || :tag) %>
<% attrs = {record: @tag,
id: target_id,
data: {form: dom_target(target_id, :form),
hidden_row: nil,
link: dom_target(target_id, :link)}} %>
<%= turbo_stream.disable attrs[:data][:link] -%>
<%= turbo_stream.append_all 'body' do %>
<%- tabular_form_with model: @tag, html: {id: attrs[:data][:form]} do |form| %>
<%= form.hidden_field :supertag_id if @tag.supertag_id? %>
<% end %>
<% end %>
<%= turbo_stream.after @tag.supertag || :tag_, partial: 'form', locals: attrs %>
@@ -0,0 +1,7 @@
<% @ancestors.each do |ancestor| %>
<%= turbo_stream.replace ancestor %>
<% end %>
<% @tags.each do |tag| %>
<%= turbo_stream.remove tag %>
<%= turbo_stream.before @before || :endmark, tag %>
<% end %>
+4
View File
@@ -0,0 +1,4 @@
<%= turbo_stream.close_form dom_target(:edit, @tag) %>
<% @ancestors.push(@tag).each do |ancestor| %>
<%= turbo_stream.replace ancestor %>
<% end %>
+10 -50
View File
@@ -1,38 +1,11 @@
# If you don't want to store sensitive information, like your database password,
# in your source code, provide the password or a full connection URL as an
# environment variable when you boot the app. For example:
#
# DATABASE_PASSWORD="Some-password1%"
#
# or
#
# DATABASE_URL="mysql2://myuser:mypass@localhost/somedatabase"
#
# If the connection URL is provided in the special DATABASE_URL environment
# variable, Rails will automatically merge its configuration values on top of
# the values provided in this file. Alternatively, you can specify a connection
# URL environment variable explicitly:
#
# production:
# url: <%= ENV["MY_APP_DATABASE_URL"] %>
#
# You can specify password environment variable in a similar way:
#
# production:
# password: <%= ENV["DATABASE_PASSWORD"] %>
#
# Read https://guides.rubyonrails.org/configuring.html#configuring-a-database
# for a full overview on how database connection configuration can be specified.
default: &default
pool: <%= ENV.fetch('RAILS_MAX_THREADS', 3) %>
#mysql_default: &mysql_default
# <<: *default
# username: fixinme
# password: Some-password1%
# host: 127.0.0.1
# encoding: utf8mb4
# collation: utf8mb4_0900_as_ci
# Disable schema dump. It is redundant with regard to migration files and
# buggy (as of Rails 8.1.4 adds foreign key constraints multiple times after
# repeated db:schema:load).
schema_dump: false
production:
<<: *default
@@ -42,27 +15,14 @@ production:
# Unless you're planning on developing the application, you can skip/remove
# configurations for development and test databases altogether.
#development:
# <<: *mysql_default
# adapter: mysql2
# database: fixinme_dev
# <<: *default
# adapter: sqlite3
# database: db/development.sqlite3
# Warning: The database(s) defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
#test:
# <<: *mysql_default
# adapter: mysql2
# database: fixinme_test
# Multiple test databases can be provided. When more than one test db is
# present, every test task (test, test:models, test:system, etc.) runs against
# all of them.
#test:
# mysql2:
# <<: *mysql_default
# adapter: mysql2
# database: fixinme_test
# sqlite3:
# <<: *default
# adapter: sqlite3
# database: db/test.sqlite3
# <<: *default
# adapter: sqlite3
# database: db/test.sqlite3
+25 -14
View File
@@ -3,24 +3,35 @@ require 'core_ext/float'
require 'core_ext/range'
ActiveSupport.on_load :action_dispatch_system_test_case do
prepend CoreExt::ActionDispatch::SystemTesting::TestHelpers::ScreenshotHelperUniqueId
# Allow denormalized string comparison,
# https://github.com/orgs/teamcapybara/discussions/2841
XPath::DSL.prepend CoreExt::XPath::DSL::NormalizeSpaceDefault
# Add timestamp to screenshot filenames to make them unique.
prepend CoreExt::ActionDispatch::SystemTesting::TestHelpers::ScreenshotHelper
# Allow denormalized string comparison:
# * https://github.com/orgs/teamcapybara/discussions/2841
XPath::DSL.prepend CoreExt::XPath::DSL
end
ActiveSupport.on_load :active_record do
# Validate that number fits into Float data type.
ActiveModel::Validations::NumericalityValidator
.prepend CoreExt::ActiveModel::Validations::NumericalityValidatesPrecision
.prepend CoreExt::ActiveModel::Validations::NumericalityValidator
# Temporary patch for https://github.com/rails/rails/pull/54658
# SELECT using window functions through SelectChain.
ActiveRecord::Relation.include CoreExt::ActiveRecord::QueryMethods
# Temporary patch for https://github.com/rails/rails/pull/54658.
ActiveRecord::Relation.include CoreExt::ActiveRecord::Relation
Arel::Crud.prepend CoreExt::Arel::Crud
Arel::Nodes::DeleteStatement.prepend CoreExt::Arel::Nodes::DeleteStatement
Arel::Nodes::UpdateStatement.prepend CoreExt::Arel::Nodes::UpdateStatement
Arel::SelectManager.prepend CoreExt::Arel::SelectManager
Arel::TreeManager::StatementMethods
.prepend CoreExt::Arel::TreeManager::StatementMethodsCteUpdateAndDelete
Arel::Nodes::DeleteStatement
.prepend CoreExt::Arel::Nodes::DeleteStatementCteUpdateAndDelete
Arel::Nodes::UpdateStatement
.prepend CoreExt::Arel::Nodes::UpdateStatementCteUpdateAndDelete
Arel::Visitors::ToSql.prepend CoreExt::Arel::Visitors::ToSqlCteUpdateAndDelete
Arel::Crud.prepend CoreExt::Arel::CrudCteUpdateAndDelete
Arel::SelectManager.prepend CoreExt::Arel::SelectManagerCteUpdateAndDelete
.prepend CoreExt::Arel::TreeManager::StatementMethods
Arel::Visitors::SQLite.prepend CoreExt::Arel::Visitors::SQLite
Arel::Visitors::ToSql.prepend CoreExt::Arel::Visitors::ToSql
# Currently not included patches for:
# * https://github.com/rails/rails/issues/59706
# * https://github.com/ruby-i18n/i18n/pull/755
# * https://github.com/teamcapybara/capybara/pull/2862
end
+24
View File
@@ -8,6 +8,9 @@ en:
out_of_range: exceeds range of double precision floating-point format
activerecord:
attributes:
tag:
description: Description
label: Label
quantity:
description: Description
name: Name
@@ -23,6 +26,14 @@ en:
status: Status
errors:
models:
tag:
attributes:
name:
taken: has to be unique
supertag:
descendant_reference: cannot be changed to any of descendants
self_reference: of the tag cannot be the tag itself
user_mismatch: has to belong to the same user as tag
unit:
attributes:
base:
@@ -104,6 +115,19 @@ en:
taken_at_html: Measurement taken at&emsp;
index:
new_measurement: Add measurement
tags:
navigation: Tags
tag:
new_subtag: Subtag
index:
new_tag: Add tag
no_items: There are no configured tags. You can Add some or Import from defaults.
create:
success: Created new tag "%{tag}"
update:
success: Updated tag "%{tag}"
destroy:
success: Deleted tag "%{tag}"
quantities:
navigation: Quantities
quantity:
+4
View File
@@ -9,6 +9,10 @@ Rails.application.routes.draw do
member { post :reparent }
end
resources :tags, except: [:show], path_names: {new: '(/:id)/new'} do
member { post :reposition }
end
resources :units, except: [:show], path_names: {new: '(/:id)/new'} do
member { post :rebase }
end
+1 -2
View File
@@ -1,11 +1,10 @@
class CreateUsers < ActiveRecord::Migration[8.1]
def change
create_table :users do |t|
t.string :email, null: false, limit: 64
t.string :email, null: false, limit: 2**6, index: {unique: true}
t.integer :status, null: false, default: 0
t.timestamps
end
add_index :users, :email
end
end
@@ -1,24 +1,24 @@
class AddDeviseToUsers < ActiveRecord::Migration[8.1]
def change
change_table :users do |t|
## NOTE: commented fields left for reference/inclusion in future migrations
## Commented fields left for reference/inclusion in future migrations.
## Database authenticatable
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.string :reset_password_token, index: {unique: true}
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Confirmable
t.string :confirmation_token
t.string :confirmation_token, index: {unique: true}
t.datetime :confirmed_at
t.datetime :confirmation_sent_at
# Only if using reconfirmable
t.string :unconfirmed_email, limit: 64
# Only if using reconfirmable.
t.string :unconfirmed_email, limit: 2**6
## Trackable
# t.integer :sign_in_count, default: 0, null: false
@@ -28,14 +28,11 @@ class AddDeviseToUsers < ActiveRecord::Migration[8.1]
# t.string :last_sign_in_ip
## Lockable
# t.string :unlock_token # Only if unlock strategy is :email or :both
# Only if unlock strategy is :email or :both.
# t.string :unlock_token, index: {unique: true}
# t.datetime :locked_at
# Only if lock strategy is :failed_attempts
# Only if lock strategy is :failed_attempts.
# t.integer :failed_attempts, default: 0, null: false
end
add_index :users, :reset_password_token
add_index :users, :confirmation_token
# add_index :users, :unlock_token, unique: true
end
end
+8 -5
View File
@@ -2,14 +2,17 @@ class CreateUnits < ActiveRecord::Migration[8.1]
def change
create_table :units do |t|
t.references :user, foreign_key: {on_delete: :cascade}
t.string :symbol, null: false, limit: 15
t.text :description
t.string :symbol, null: false, limit: 2**4
t.text :description, limit: 2**16
t.float :multiplier, null: false, limit: Float::MANT_DIG, default: 1.0
t.references :base, foreign_key: {to_table: :units, on_delete: :cascade}
t.timestamps
# Constraints:
# * symbol has to be unique
t.index [:user_id, :symbol], unique: true
# * unit has to belong to the same user as quantity (used by :readouts)
t.index [:id, :user_id], unique: true
end
add_index :units, [:user_id, :symbol]
add_index :units, [:id, :user_id]
end
end
+11 -8
View File
@@ -2,17 +2,20 @@ class CreateQuantities < ActiveRecord::Migration[8.1]
def change
create_table :quantities do |t|
t.references :user, foreign_key: {on_delete: :cascade}
t.string :name, null: false, limit: 31
t.text :description
t.string :name, null: false, limit: 2**5
t.text :description, limit: 2**16
t.references :parent, foreign_key: {to_table: :quantities, on_delete: :cascade}
t.timestamps
# Caches; can be computed from other attributes
t.integer :depth, null: false, default: 0
# Cached, computed from other attributes. NULL default to ensure value
# has been properly initialized.
t.integer :depth, null: false
t.string :pathname, null: false, limit: 511
# Constraints:
# * name has to be unique
t.index [:user_id, :parent_id, :name], unique: true
# * quantity has to belong to the same user as unit (used by :readouts)
t.index [:id, :user_id], unique: true
end
add_index :quantities, [:user_id, :parent_id, :name]
add_index :quantities, [:id, :user_id]
end
end
+10 -11
View File
@@ -1,20 +1,17 @@
class CreateReadouts < ActiveRecord::Migration[8.1]
def change
create_table :notes do |t|
t.text :text, null: false
t.text :text, null: false, limit: 2**16
t.timestamps
end
create_table :measurements do |t|
t.datetime :taken_at, null: false
t.datetime :taken_at, null: false, index: {unique: true}
#t.references :collector, foreign_key: true
#t.references :device, foreign_key: true
t.references :note, foreign_key: {on_delete: :nullify}
t.timestamps
end
add_index :measurements, :taken_at
# Defining Readouts as a super-/subclass polymorphic relations for different
# subclass data types (numeric, string, file) is not possible with proper
@@ -40,14 +37,16 @@ class CreateReadouts < ActiveRecord::Migration[8.1]
# t.references :file
# Possibly mutually exclusive with :unit or check constraint for:
# :unit is not null <=> :value is not null
t.timestamps
# Constraints:
# * quantity + category has to be unique within measurement
t.index [:measurement_id, :quantity_id, :category], unique: true
# * quantity and unit has to belong to the same user as readout
t.foreign_key :quantities, column: [:quantity_id, :user_id],
primary_key: [:id, :user_id]
t.foreign_key :units, column: [:unit_id, :user_id], primary_key: [:id, :user_id]
end
add_index :readouts, [:measurement_id, :quantity_id, :category]
add_foreign_key :readouts, :quantities, column: [:quantity_id, :user_id],
primary_key: [:id, :user_id]
add_foreign_key :readouts, :units, column: [:unit_id, :user_id],
primary_key: [:id, :user_id]
# TODO: remove below tables after current setup verified
#create_table :numeric_values do |t|
+24
View File
@@ -0,0 +1,24 @@
class CreateTags < ActiveRecord::Migration[8.1]
def change
create_table :tags do |t|
t.references :user, null: false, foreign_key: {on_delete: :cascade}
t.string :label, null: false, limit: 2**5
t.text :description, limit: 2**16
t.references :supertag, foreign_key: {to_table: :tags, on_delete: :cascade}
t.timestamps
# Cached, computed from other attributes. NULL default to ensure value
# has been properly initialized.
t.integer :depth, null: false
# Constraints:
# * label has to be unique
t.index [:user_id, :label], unique: true
# * supertag cannot reference self
t.check_constraint 'id != supertag_id', name: :self_reference
# * supertag has to belong to the same user as tag
t.index [:id, :user_id], unique: true
t.foreign_key :tags, primary_key: [:id, :user_id],
column: [:supertag_id, :user_id], name: :user_mismatch
end
end
end
-105
View File
@@ -1,105 +0,0 @@
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `bin/rails
# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[8.1].define(version: 2025_01_21_230456) do
create_table "measurements", charset: "utf8mb4", collation: "utf8mb4_0900_as_ci", force: :cascade do |t|
t.datetime "taken_at", null: false
t.bigint "note_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["note_id"], name: "index_measurements_on_note_id"
t.index ["taken_at"], name: "index_measurements_on_taken_at", unique: true
end
create_table "notes", charset: "utf8mb4", collation: "utf8mb4_0900_as_ci", force: :cascade do |t|
t.text "text", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "quantities", charset: "utf8mb4", collation: "utf8mb4_0900_as_ci", force: :cascade do |t|
t.bigint "user_id"
t.string "name", limit: 31, null: false
t.text "description"
t.bigint "parent_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "depth", default: 0, null: false
t.string "pathname", limit: 511, null: false
t.index ["id", "user_id"], name: "index_quantities_on_id_and_user_id", unique: true
t.index ["parent_id"], name: "index_quantities_on_parent_id"
t.index ["user_id", "parent_id", "name"], name: "index_quantities_on_user_id_and_parent_id_and_name", unique: true
t.index ["user_id"], name: "index_quantities_on_user_id"
end
create_table "readouts", charset: "utf8mb4", collation: "utf8mb4_0900_as_ci", force: :cascade do |t|
t.bigint "user_id", null: false
t.bigint "measurement_id"
t.bigint "quantity_id", null: false
t.integer "category", default: 0, null: false
t.float "value", limit: 53, null: false
t.bigint "unit_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["measurement_id", "quantity_id", "category"], name: "index_readouts_on_measurement_id_and_quantity_id_and_category", unique: true
t.index ["measurement_id"], name: "index_readouts_on_measurement_id"
t.index ["quantity_id", "user_id"], name: "fk_rails_9d92eaafc6"
t.index ["quantity_id"], name: "index_readouts_on_quantity_id"
t.index ["unit_id", "user_id"], name: "fk_rails_348b0fb4c5"
t.index ["unit_id"], name: "index_readouts_on_unit_id"
t.index ["user_id"], name: "index_readouts_on_user_id"
end
create_table "units", charset: "utf8mb4", collation: "utf8mb4_0900_as_ci", force: :cascade do |t|
t.bigint "user_id"
t.string "symbol", limit: 15, null: false
t.text "description"
t.float "multiplier", limit: 53, default: 1.0, null: false
t.bigint "base_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["base_id"], name: "index_units_on_base_id"
t.index ["id", "user_id"], name: "index_units_on_id_and_user_id", unique: true
t.index ["user_id", "symbol"], name: "index_units_on_user_id_and_symbol", unique: true
t.index ["user_id"], name: "index_units_on_user_id"
end
create_table "users", charset: "utf8mb4", collation: "utf8mb4_0900_as_ci", force: :cascade do |t|
t.string "email", limit: 64, null: false
t.integer "status", default: 0, null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "unconfirmed_email", limit: 64
t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
add_foreign_key "measurements", "notes", on_delete: :nullify
add_foreign_key "quantities", "quantities", column: "parent_id", on_delete: :cascade
add_foreign_key "quantities", "users", on_delete: :cascade
add_foreign_key "readouts", "measurements", on_delete: :cascade
add_foreign_key "readouts", "quantities", column: ["quantity_id", "user_id"], primary_key: ["id", "user_id"]
add_foreign_key "readouts", "quantities", on_delete: :cascade
add_foreign_key "readouts", "units", column: ["unit_id", "user_id"], primary_key: ["id", "user_id"]
add_foreign_key "readouts", "units", on_delete: :cascade
add_foreign_key "readouts", "users", on_delete: :cascade
add_foreign_key "units", "units", column: "base_id", on_delete: :cascade
add_foreign_key "units", "users", on_delete: :cascade
end
-103
View File
@@ -1,103 +0,0 @@
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `bin/rails
# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[8.1].define(version: 2025_01_21_230456) do
create_table "measurements", force: :cascade do |t|
t.datetime "taken_at", null: false
t.integer "note_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["note_id"], name: "index_measurements_on_note_id"
t.index ["taken_at"], name: "index_measurements_on_taken_at", unique: true
end
create_table "notes", force: :cascade do |t|
t.text "text", limit: 65535, null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "quantities", force: :cascade do |t|
t.integer "user_id"
t.string "name", limit: 31, null: false
t.text "description", limit: 65535
t.integer "parent_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "depth", default: 0, null: false
t.string "pathname", limit: 511, null: false
t.index ["id", "user_id"], name: "index_quantities_on_id_and_user_id", unique: true
t.index ["parent_id"], name: "index_quantities_on_parent_id"
t.index ["user_id", "parent_id", "name"], name: "index_quantities_on_user_id_and_parent_id_and_name", unique: true
t.index ["user_id"], name: "index_quantities_on_user_id"
end
create_table "readouts", force: :cascade do |t|
t.integer "user_id", null: false
t.integer "measurement_id"
t.integer "quantity_id", null: false
t.integer "category", default: 0, null: false
t.float "value", limit: 53, null: false
t.integer "unit_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["measurement_id", "quantity_id", "category"], name: "index_readouts_on_measurement_id_and_quantity_id_and_category", unique: true
t.index ["measurement_id"], name: "index_readouts_on_measurement_id"
t.index ["quantity_id"], name: "index_readouts_on_quantity_id"
t.index ["unit_id"], name: "index_readouts_on_unit_id"
t.index ["user_id"], name: "index_readouts_on_user_id"
end
create_table "units", force: :cascade do |t|
t.integer "user_id"
t.string "symbol", limit: 15, null: false
t.text "description", limit: 65535
t.float "multiplier", limit: 53, default: 1.0, null: false
t.integer "base_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["base_id"], name: "index_units_on_base_id"
t.index ["id", "user_id"], name: "index_units_on_id_and_user_id", unique: true
t.index ["user_id", "symbol"], name: "index_units_on_user_id_and_symbol", unique: true
t.index ["user_id"], name: "index_units_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "email", limit: 64, null: false
t.integer "status", default: 0, null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "unconfirmed_email", limit: 64
t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
add_foreign_key "measurements", "notes", on_delete: :nullify
add_foreign_key "quantities", "quantities", column: "parent_id", on_delete: :cascade
add_foreign_key "quantities", "users", on_delete: :cascade
add_foreign_key "readouts", "measurements", on_delete: :cascade
add_foreign_key "readouts", "quantities", column: ["quantity_id", "user_id"], primary_key: ["id", "user_id"]
add_foreign_key "readouts", "quantities", on_delete: :cascade
add_foreign_key "readouts", "units", column: ["unit_id", "user_id"], primary_key: ["id", "user_id"]
add_foreign_key "readouts", "units", on_delete: :cascade
add_foreign_key "readouts", "users", on_delete: :cascade
add_foreign_key "units", "units", column: "base_id", on_delete: :cascade
add_foreign_key "units", "users", on_delete: :cascade
end
@@ -1,4 +1,4 @@
module CoreExt::ActionDispatch::SystemTesting::TestHelpers::ScreenshotHelperUniqueId
module CoreExt::ActionDispatch::SystemTesting::TestHelpers::ScreenshotHelper
private
def unique
@@ -1,4 +1,4 @@
module CoreExt::ActiveModel::Validations::NumericalityValidatesPrecision
module CoreExt::ActiveModel::Validations::NumericalityValidator
def validate_each(record, attr_name, value, **kwargs)
super(record, attr_name, value, **kwargs)
@@ -0,0 +1,39 @@
module CoreExt::ActiveRecord::QueryMethods
class SelectChain
def initialize(scope)
@scope = scope
end
def lag(expr, offset: 1, default: nil)
case expr
when Hash
when Symbol
expr = {expr => "lag_#{expr}"}
else
raise ArgumentError, "Unsupported expression argument type: #{expr.class.name}."
end
expr.each do |column, column_alias|
@scope._select!(
Arel::Nodes::NamedFunction.new(
'LAG',
[@scope.table[column], offset, Arel::Nodes.build_quoted(default)]
).over().as(column_alias)
)
end
@scope
end
end
def self.included(base)
base.prepend SelectWithSelectChain
end
end
module SelectWithSelectChain
def select(*fields)
return super if !fields.empty? || block_given?
ActiveRecord::Relation::SelectChain.new(spawn)
end
end
+6
View File
@@ -0,0 +1,6 @@
module CoreExt::ActiveRecord::Relation
ActiveRecord::Relation.class_eval do
remove_const :INVALID_METHODS_FOR_UPDATE_AND_DELETE_ALL
INVALID_METHODS_FOR_UPDATE_AND_DELETE_ALL = [:distinct]
end
end
@@ -1,3 +0,0 @@
module CoreExt::ActiveRecord::Relation::UpdateAndDeleteCteSupport
INVALID_METHODS_FOR_UPDATE_AND_DELETE_ALL = [:distinct]
end
@@ -1,4 +1,4 @@
module CoreExt::Arel::CrudCteUpdateAndDelete
module CoreExt::Arel::Crud
def compile_update(...)
um = super
um.with = subqueries
@@ -1,4 +1,4 @@
module CoreExt::Arel::Nodes::DeleteStatementCteUpdateAndDelete
module CoreExt::Arel::Nodes::DeleteStatement
attr_accessor :with
def initialize(...)
@@ -1,4 +1,4 @@
module CoreExt::Arel::Nodes::UpdateStatementCteUpdateAndDelete
module CoreExt::Arel::Nodes::UpdateStatement
attr_accessor :with
def initialize(...)
+5
View File
@@ -0,0 +1,5 @@
module CoreExt::Arel::SelectManager
def subqueries
@ast.with
end
end
@@ -1,5 +0,0 @@
module CoreExt::Arel::SelectManagerCteUpdateAndDelete
def subqueries
@ast.with
end
end
@@ -0,0 +1,6 @@
module CoreExt::Arel::TreeManager::StatementMethods
def with=(expr)
@ast.with = expr
self
end
end
@@ -1,6 +0,0 @@
module CoreExt::Arel::TreeManager::StatementMethodsCteUpdateAndDelete
def with=(expr)
@ast.with = expr
self
end
end
+10
View File
@@ -0,0 +1,10 @@
module CoreExt::Arel::Visitors::SQLite
def visit_Arel_Nodes_UpdateStatement(o, collector)
if o.with
collector = visit o.with, collector
collector << " "
end
super
end
end
+10
View File
@@ -0,0 +1,10 @@
module CoreExt::Arel::Visitors::ToSql
def visit_Arel_Nodes_DeleteStatement(o, collector)
if o.with
collector = visit o.with, collector
collector << " "
end
super
end
end
@@ -1,19 +0,0 @@
module CoreExt::Arel::Visitors::ToSqlCteUpdateAndDelete
def visit_Arel_Nodes_DeleteStatement(o, collector)
if o.with
collector = visit o.with, collector
collector << " "
end
super
end
def visit_Arel_Nodes_UpdateStatement(o, collector)
if o.with
collector = visit o.with, collector
collector << " "
end
super
end
end
@@ -1,4 +1,4 @@
module CoreExt::XPath::DSL::NormalizeSpaceDefault
module CoreExt::XPath::DSL
def normalize_space(...)
Capybara.default_normalize_ws ? super : current
end
+71 -41
View File
@@ -1,55 +1,85 @@
class DefaultSettingsStrategy < ActiveRecord::Migration::DefaultStrategy
COLUMN_DEFAULTS = {
# TODO: all types `null: false` ?
# TODO: references `foreign_key: {on_delete: :cascade}` ?
# `timestamps` - Rails defaults to `null: false, precision: true`.
# `limit:` for `text` - `text` can be theoretically up to 1GB or
# longer, so roughly unlimited for practical purposes. But:
# * the actual usable length depends on additional factors, like compile
# time limits (`SQLITE_MAX_LENGTH` in SQLite), runtime settings
# (`max_allowed_packet` in MySQL) and probably other,
# * Rails does not report limit for `text` column types, unless it is
# explicitly set.
# The decision is to always set safe limit and enforce it by validations, to
# avoid surprises (e.g. text truncation) when saving to dabatase.
text: {limit: 2**16 - 1}
}
COLUMN_DEFAULTS.default = {}
COLUMN_DEFAULTS.freeze
# Strategy methods can be invoked differently depending on whether changes are
# applied from migration files in up or down direction (e.g. `change_table`
# can be run as series of `remove_column` during #down) or from schema file.
# Strategy has to be verified at least using:
# db:migrate + db:migrate VERSION=0
# db:reset + (multiple) db:schema:load (if schema file is used)
module ColumnSettingsStrategy
def column(name, type, **options)
super(name, type, **COLUMN_DEFAULTS[type].merge(options))
def method_missing(method, *args, **kwargs, &)
return super if migration.reverting?
# SchemaDumper#table has hardcoded: `tbl.puts ", force: :cascade do |t|"`.
# It collides with `if_not_exists`. Drop #except(*conflicts) after
# https://github.com/rails/rails/issues/37392 is fixed.
defaults = MIGRATION_DEFAULTS[method.to_sym]
conflicts = defaults.has_key?(:if_not_exists) ? [:force] : []
result = nil
process_method(method, *args, **kwargs) do
result = super(method, *args, **defaults.merge(kwargs.except(*conflicts)), &)
end
return result
end
def process_method(method, *args, **kwargs)
case method.to_sym
when :create_table
yield
add_constraints(args.first, columns(args.first))
when :change_table
before, _, after = columns(args.first), yield, columns(args.first)
add_constraints(args.first, after - before)
remove_constraints(args.first, (before - after).map(&:name))
when :remove_column
remove_constraints(args.first, [args.second])
yield
else
yield
end
end
ActiveRecord::ConnectionAdapters::TableDefinition.prepend ColumnSettingsStrategy
# `force: :cascade` - does nothing on MySQL, so `force:` is useless.
# `if_not_exists: true`/`if_exists: true` - without these options it's impossible
# to change migration status once migration fails partially. If `up` migration
# creates some, but not all objects, its status is not updated from `down` to
# `up`. Then it's impossible to migrate: a) up - due to `already exists`
# errors and b) down - due to migration status.
private
# `if_not_exists: true`/`if_exists: true` - are necessary fo every top level
# migration statement. Without these options it's impossible to change
# migration status once it fails in the middle. If migration is only applied
# partially, its status is not updated. Then it's impossible to:
# a) migrate, because some objects have alredy been created/dropped and
# b) rollback, due to migration status.
# `timestamps` - Rails defaults to `null: false, precision: true`, as expected.
MIGRATION_DEFAULTS = {
add_check_constraint: {if_not_exists: true},
add_column: {if_not_exists: true},
add_foreign_key: {if_not_exists: true},
add_index: {if_not_exists: true, unique: true},
add_timestamps: {if_not_exists: true},
create_table: {if_not_exists: true},
add_check_constraint: {if_not_exists: true},
create_table: {if_not_exists: true},
drop_table: {if_exists: true},
remove_check_constraint: {if_exists: true},
remove_column: {if_exists: true},
remove_foreign_key: {if_exists: true},
remove_index: {if_exists: true},
remove_timestamps: {if_exists: true},
}
MIGRATION_DEFAULTS.default = {}
MIGRATION_DEFAULTS.freeze
def method_missing(method, *args, **kwargs, &)
conflicts = kwargs.has_key?(:force) ? [:if_not_exists, :if_exists] : []
defaults = MIGRATION_DEFAULTS[method.to_sym].except(*conflicts)
super(method, *args, **defaults.merge(kwargs), &)
# SQLite does not enforce `limit` on string/text columns by default. `text`
# can be theoretically up to 1GB or longer, so roughly unlimited for practical
# purposes. But the actual usable length depends on additional factors, like
# compile time limits (`SQLITE_MAX_LENGTH` in SQLite) and probably other.
# Limit is explicitly set to:
# a) be used by views/UI (Rails does not report limit for `text` column
# types, unless it is explicitly set) and
# b) be enforced by database constraint (below).
# Length constraint is measured in codepoints (not bytes).
def add_constraints(table_name, columns)
# Do not run on db:schema:load, as constraints are dumped explicitly.
return unless migration.name
columns.select { |column| column.limit && [:string, :text].include?(column.type) }
.each do |column|
expression = "length(#{column.name}) <= #{column.limit}"
name = "#{column.name}_length"
add_check_constraint(table_name, expression, name: name)
end
end
def remove_constraints(table_name, column_names)
column_names.each do |column_name|
remove_check_constraint(table_name, name: "#{column_name}_length")
end
end
end
+19 -28
View File
@@ -4,7 +4,7 @@ require "test_helper"
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
include ActionView::Helpers::UrlHelper
# NOTE: geckodriver installed with Firefox, ignore incompatibility warning
# `geckodriver` installed with Firefox, ignore incompatibility warning.
Selenium::WebDriver.logger
.ignore(:selenium_manager, :clear_session_storage, :clear_local_storage)
@@ -33,33 +33,24 @@ class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
button.html_safe)
end
DB_CONFIGS = ActiveRecord::Base.configurations.configs_for(env_name: "test")
TEST_CONFIGS = Hash.new(DB_CONFIGS.first.name.to_sym)
class << self
# NOTE: alternative to current solution is to create shards:
# ActiveRecord::Base.connects_to(
# shards: {mysql2: {writing: :mysql2}, sqlite3: {writing: :sqlite3}}
# )
# and use them in one of the following ways:
# * set config.active_record.shard_selector/shard_resolver
# * run tests within: ActiveRecord::Base.connected_to(shard: :sqlite3) { test_ }
# Remove this note once current solution is confirmed to work.
#
# Test block should not be modified here, as it would change its binding from
# instance level to class level.
# TODO: allow multiple iterations of tests? would require saving seed in
# #setup to make reproducing easier
if DB_CONFIGS.many?
def test(name, ...)
DB_CONFIGS.each do |config|
TEST_CONFIGS[super("#{config.name} #{name}", ...)] = config.name.to_sym
end
end
end
end
setup do
ActiveRecord::Base.establish_connection(TEST_CONFIGS[name.to_sym])
end
#DB_CONFIGS = ActiveRecord::Base.configurations.configs_for(env_name: "test")
#TEST_CONFIGS = Hash.new(DB_CONFIGS.first.name.to_sym)
#class << self
# # Test block should not be modified here, as it would change its binding from
# # instance level to class level.
# # TODO: allow multiple iterations of tests? would require saving seed in
# # #setup to make reproducing easier
# if DB_CONFIGS.many?
# def test(name, ...)
# DB_CONFIGS.each do |config|
# TEST_CONFIGS[super("#{config.name} #{name}", ...)] = config.name.to_sym
# end
# end
# end
#end
#setup do
# ActiveRecord::Base.establish_connection(TEST_CONFIGS[name.to_sym])
#end
Capybara.modify_selector(:link) do
expression_filter(:disabled) do |xpath, value|