This commit is contained in:
2026-11-23 18:42:15 +01:00
parent 978217b3be
commit 74f9a09098
24 changed files with 445 additions and 10 deletions
@@ -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
+4 -1
View File
@@ -1,3 +1,6 @@
module CoreExt::ActiveRecord::Relation
INVALID_METHODS_FOR_UPDATE_AND_DELETE_ALL = [:distinct]
ActiveRecord::Relation.class_eval do
remove_const :INVALID_METHODS_FOR_UPDATE_AND_DELETE_ALL
INVALID_METHODS_FOR_UPDATE_AND_DELETE_ALL = [:distinct]
end
end
+13 -8
View File
@@ -4,14 +4,6 @@ class DefaultSettingsStrategy < ActiveRecord::Migration::DefaultStrategy
# TODO: references `foreign_key: {on_delete: :cascade}` ?
# `timestamps` - Rails defaults to `null: false, precision: true`, which is
# expected.
# `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) 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 = {}
@@ -20,6 +12,19 @@ class DefaultSettingsStrategy < ActiveRecord::Migration::DefaultStrategy
module ColumnSettingsStrategy
def column(name, type, **options)
super(name, type, **COLUMN_DEFAULTS[type].merge(options))
# 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).
if options[:limit] && [:string, :text].include?(type)
check_constraint("length(#{name}) <= #{options[:limit]}", name: "#{name}_length")
end
end
end
ActiveRecord::ConnectionAdapters::TableDefinition.prepend ColumnSettingsStrategy