From e693fe2a20bd9200f0b2f712d60783a97db6f3c6 Mon Sep 17 00:00:00 2001 From: Nikita Shilnikov Date: Fri, 3 Jan 2025 11:47:23 +0100 Subject: [PATCH] rubocop -a --- .rubocop.yml | 4 + Rakefile | 2 +- .../plugins/relation/sql/auto_restrictions.rb | 2 +- .../plugins/relation/sql/instrumentation.rb | 8 +- .../relation/sql/postgres/full_text_search.rb | 8 +- .../relation/sql/postgres/streaming.rb | 12 +- lib/rom/sql/associations/many_to_many.rb | 6 +- lib/rom/sql/attribute.rb | 12 +- lib/rom/sql/attribute_aliasing.rb | 13 +- lib/rom/sql/commands/create.rb | 7 +- lib/rom/sql/commands/update.rb | 7 +- .../active_support_notifications.rb | 2 +- .../sql/extensions/postgres/type_builder.rb | 14 +- .../extensions/postgres/type_serializer.rb | 4 +- .../extensions/postgres/types/geometric.rb | 24 +- .../sql/extensions/postgres/types/ltree.rb | 87 +++-- .../sql/extensions/postgres/types/range.rb | 8 +- .../sql/extensions/rails_log_subscriber.rb | 6 +- lib/rom/sql/gateway.rb | 12 +- lib/rom/sql/group_dsl.rb | 4 +- lib/rom/sql/migration.rb | 4 +- lib/rom/sql/migration/inline_runner.rb | 4 +- lib/rom/sql/migration/migrator.rb | 10 +- lib/rom/sql/migration/schema_diff.rb | 9 +- lib/rom/sql/migration/writer.rb | 16 +- lib/rom/sql/order_dsl.rb | 4 +- lib/rom/sql/plugin/associates.rb | 17 +- lib/rom/sql/plugin/pagination.rb | 2 +- lib/rom/sql/projection_dsl.rb | 2 +- lib/rom/sql/relation.rb | 12 +- lib/rom/sql/relation/reading.rb | 77 ++-- lib/rom/sql/relation/writing.rb | 28 +- lib/rom/sql/restriction_dsl.rb | 4 +- lib/rom/sql/schema.rb | 14 +- lib/rom/sql/schema/attributes_inferrer.rb | 2 +- lib/rom/sql/schema/dsl.rb | 4 +- lib/rom/sql/schema/index_dsl.rb | 6 +- lib/rom/sql/schema/inferrer.rb | 34 +- lib/rom/sql/schema/type_builder.rb | 4 +- lib/rom/sql/tasks/migration_tasks.rake | 9 +- lib/rom/sql/type_dsl.rb | 10 +- lib/rom/sql/type_extensions.rb | 8 +- lib/rom/sql/type_serializer.rb | 4 +- lib/rom/sql/types.rb | 4 +- lib/rom/sql/version.rb | 2 +- lib/rom/types/values.rb | 2 +- .../postgres/attribute/array_spec.rb | 2 + .../postgres/attribute/range_spec.rb | 8 +- spec/extensions/postgres/attribute_spec.rb | 334 +++++++++++------- spec/extensions/postgres/integration_spec.rb | 6 +- .../postgres/type_serializer_spec.rb | 6 +- spec/extensions/postgres/types_meta_spec.rb | 12 +- spec/extensions/postgres/types_spec.rb | 8 +- spec/extensions/sqlite/types_spec.rb | 2 + .../20150403090603_create_carrots.rb | 2 + spec/integration/commands/create_spec.rb | 1 + .../schema/inferrer/postgres_spec.rb | 16 +- 57 files changed, 545 insertions(+), 386 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index 8a8f2e0c2..3c4fc3ece 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -89,6 +89,10 @@ Naming/MethodName: Naming/MethodParameterName: Enabled: false +Style/MultilineBlockChain: + Exclude: + - "spec/**/*.rb" + Style/MutableConstant: Exclude: - "spec/**/*.rb" diff --git a/Rakefile b/Rakefile index 571441d1a..51f289b88 100644 --- a/Rakefile +++ b/Rakefile @@ -1,4 +1,4 @@ -require "rspec/core/rake_task" +require 'rspec/core/rake_task' RSpec::Core::RakeTask.new(:spec) diff --git a/lib/rom/plugins/relation/sql/auto_restrictions.rb b/lib/rom/plugins/relation/sql/auto_restrictions.rb index 849c3d3a5..6172cccae 100644 --- a/lib/rom/plugins/relation/sql/auto_restrictions.rb +++ b/lib/rom/plugins/relation/sql/auto_restrictions.rb @@ -46,7 +46,7 @@ def self.restriction_methods(schema) next if index.partial? attributes = index.to_a - meth_name = :"by_#{ attributes.map(&:name).join('_and_') }" + meth_name = :"by_#{attributes.map(&:name).join("_and_")}" next if generated.include?(meth_name) diff --git a/lib/rom/plugins/relation/sql/instrumentation.rb b/lib/rom/plugins/relation/sql/instrumentation.rb index 7a58ebedc..2c344b562 100644 --- a/lib/rom/plugins/relation/sql/instrumentation.rb +++ b/lib/rom/plugins/relation/sql/instrumentation.rb @@ -31,8 +31,12 @@ module Instrumentation subscribe('configuration.relations.registry.created') do |event| registry = event[:registry] - relations = registry.select { |_, r| r.adapter == :sql && r.respond_to?(:notifications) }.to_h - db_notifications = relations.values.map { |r| [r.dataset.db, r.notifications] }.uniq.to_h + relations = registry.select { |_, r| + r.adapter == :sql && r.respond_to?(:notifications) + }.to_h + db_notifications = relations.values.map { |r| + [r.dataset.db, r.notifications] + }.uniq.to_h db_notifications.each do |db, notifications| next if db.respond_to?(:rom_instrumentation?) diff --git a/lib/rom/plugins/relation/sql/postgres/full_text_search.rb b/lib/rom/plugins/relation/sql/postgres/full_text_search.rb index 682c67a1d..f0ecffb5f 100644 --- a/lib/rom/plugins/relation/sql/postgres/full_text_search.rb +++ b/lib/rom/plugins/relation/sql/postgres/full_text_search.rb @@ -36,8 +36,8 @@ module FullTextSearch # @see https://www.postgresql.org/docs/current/textsearch.html PostgreSQL docs # # @api public - def full_text_search(*args, &block) - new dataset.__send__(__method__, *args, &block) + def full_text_search(...) + new dataset.__send__(__method__, ...) end end end @@ -48,6 +48,8 @@ def full_text_search(*args, &block) ROM.plugins do adapter :sql do - register :pg_full_text_search, ROM::Plugins::Relation::SQL::Postgres::FullTextSearch, type: :relation + register :pg_full_text_search, + ROM::Plugins::Relation::SQL::Postgres::FullTextSearch, + type: :relation end end diff --git a/lib/rom/plugins/relation/sql/postgres/streaming.rb b/lib/rom/plugins/relation/sql/postgres/streaming.rb index 2e63b2a4e..84bd23136 100644 --- a/lib/rom/plugins/relation/sql/postgres/streaming.rb +++ b/lib/rom/plugins/relation/sql/postgres/streaming.rb @@ -13,7 +13,7 @@ module Streaming class StreamingNotSupportedError < StandardError; end - subscribe("configuration.gateway.connected") do |opts| + subscribe('configuration.gateway.connected') do |opts| conn = opts[:connection] next unless conn.database_type.to_sym == :postgres @@ -21,13 +21,13 @@ class StreamingNotSupportedError < StandardError; end next if defined?(JRUBY_VERSION) begin - require "sequel_pg" + require 'sequel_pg' rescue LoadError - raise StreamingNotSupportedError, "add sequel_pg to Gemfile to use pg_streaming" + raise StreamingNotSupportedError, 'add sequel_pg to Gemfile to use pg_streaming' end unless Sequel::Postgres.supports_streaming? - raise StreamingNotSupportedError, "postgres version does not support streaming" + raise StreamingNotSupportedError, 'postgres version does not support streaming' end conn.extension(:pg_streaming) @@ -52,7 +52,7 @@ def self.included(klass) # # @api publicY_VERSION def stream_each - raise StreamingNotSupportedError, "not supported on jruby" + raise StreamingNotSupportedError, 'not supported on jruby' end else # Allows you to stream returned rows one at a time, instead of @@ -80,7 +80,7 @@ def stream_each module Combined def stream_each - raise StreamingNotSupportedError, "not supported on combined relations" + raise StreamingNotSupportedError, 'not supported on combined relations' end end diff --git a/lib/rom/sql/associations/many_to_many.rb b/lib/rom/sql/associations/many_to_many.rb index 9c7241c3f..f0247d49f 100644 --- a/lib/rom/sql/associations/many_to_many.rb +++ b/lib/rom/sql/associations/many_to_many.rb @@ -17,10 +17,10 @@ def call(target: self.target) schema = if left.schema.key?(foreign_key) - if target != self.target - target.schema.merge(join_schema) - else + if target == self.target left.schema.uniq.project(*columns) + else + target.schema.merge(join_schema) end else target_schema diff --git a/lib/rom/sql/attribute.rb b/lib/rom/sql/attribute.rb index f05fffda1..716946c13 100644 --- a/lib/rom/sql/attribute.rb +++ b/lib/rom/sql/attribute.rb @@ -263,8 +263,8 @@ def in(*args) # @return [SQL::Function] # # @api public - def func(&block) - ProjectionDSL.new(name => self).call(&block).first + def func(&) + ProjectionDSL.new(name => self).call(&).first end # Create a CONCAT function from the attribute @@ -380,19 +380,19 @@ def case(mapping) # # @api private def sql_expr - @sql_expr ||= (meta[:sql_expr] || to_sql_name) + @sql_expr ||= meta[:sql_expr] || to_sql_name end # Delegate to sql expression if it responds to a given method # # @api private - def method_missing(meth, *args, &block) + def method_missing(meth, *args, &) if OPERATORS.include?(meth) __cmp__(meth, args[0]) elsif extensions.key?(meth) - extensions[meth].(type, sql_expr, *args, &block) + extensions[meth].(type, sql_expr, *args, &) elsif sql_expr.respond_to?(meth) - meta(sql_expr: sql_expr.__send__(meth, *args, &block)) + meta(sql_expr: sql_expr.__send__(meth, *args, &)) else super end diff --git a/lib/rom/sql/attribute_aliasing.rb b/lib/rom/sql/attribute_aliasing.rb index da6e6e06d..33611a132 100644 --- a/lib/rom/sql/attribute_aliasing.rb +++ b/lib/rom/sql/attribute_aliasing.rb @@ -19,8 +19,7 @@ def aliased(alias_name) sql_expr: alias_sql_expr(sql_expr, new_alias_name) ) end - alias as aliased - + alias_method :as, :aliased # Return true if this attribute is an aliased projection # @@ -46,7 +45,7 @@ def aliased(alias_name) # # @api private def aliased_projection? - self.meta[:sql_expr].is_a?(Sequel::SQL::AliasedExpression) + meta[:sql_expr].is_a?(::Sequel::SQL::AliasedExpression) end private @@ -54,8 +53,10 @@ def aliased_projection? # @api private def alias_sql_expr(sql_expr, new_alias) case sql_expr - when Sequel::SQL::AliasedExpression - Sequel::SQL::AliasedExpression.new(sql_expr.expression, new_alias, sql_expr.columns) + when ::Sequel::SQL::AliasedExpression + ::Sequel::SQL::AliasedExpression.new( + sql_expr.expression, new_alias, sql_expr.columns + ) else sql_expr.as(new_alias) end @@ -70,7 +71,7 @@ def extract_alias_names(alias_name) # attribute in a way that will map the the requested alias name. # Without this, the attribute will silently ignore the requested alias # name and default to the pre-existing name. - new_name = "#{meta[:wrapped]}_#{options[:alias]}".to_sym + new_name = :"#{meta[:wrapped]}_#{options[:alias]}" # Essentially, this makes it so "wrapped" attributes aren't true # aliases, in that we actually alias the wrapped attribute, we use diff --git a/lib/rom/sql/commands/create.rb b/lib/rom/sql/commands/create.rb index 206b76f14..446279958 100644 --- a/lib/rom/sql/commands/create.rb +++ b/lib/rom/sql/commands/create.rb @@ -60,10 +60,11 @@ def multi_insert(tuples) # Yields tuples for insertion or return an enumerator # # @api private - def with_input_tuples(tuples) - input_tuples = Array([tuples]).flatten(1).map + def with_input_tuples(tuples, &) + input_tuples = [tuples].flatten(1).map return input_tuples unless block_given? - input_tuples.each { |tuple| yield(tuple) } + + input_tuples.each(&) end end end diff --git a/lib/rom/sql/commands/update.rb b/lib/rom/sql/commands/update.rb index aaa9f6502..775991770 100644 --- a/lib/rom/sql/commands/update.rb +++ b/lib/rom/sql/commands/update.rb @@ -52,10 +52,11 @@ def primary_key # Yields tuples for insertion or return an enumerator # # @api private - def with_input_tuples(tuples) - input_tuples = Array([tuples]).flatten(1).map + def with_input_tuples(tuples, &) + input_tuples = [tuples].flatten(1).map return input_tuples unless block_given? - input_tuples.each { |tuple| yield(tuple) } + + input_tuples.each(&) end end end diff --git a/lib/rom/sql/extensions/active_support_notifications.rb b/lib/rom/sql/extensions/active_support_notifications.rb index 88957b713..0626d88cb 100644 --- a/lib/rom/sql/extensions/active_support_notifications.rb +++ b/lib/rom/sql/extensions/active_support_notifications.rb @@ -24,4 +24,4 @@ def instrumentation_name end end -Sequel::Database.send(:prepend, ROM::SQL::ActiveSupportInstrumentation) +Sequel::Database.prepend ROM::SQL::ActiveSupportInstrumentation diff --git a/lib/rom/sql/extensions/postgres/type_builder.rb b/lib/rom/sql/extensions/postgres/type_builder.rb index ae0ecc242..1970d326f 100644 --- a/lib/rom/sql/extensions/postgres/type_builder.rb +++ b/lib/rom/sql/extensions/postgres/type_builder.rb @@ -6,17 +6,17 @@ module Postgres class TypeBuilder < Schema::TypeBuilder defines :db_numeric_types, :db_type_mapping, :db_array_type_matcher - db_numeric_types %w[ - smallint integer bigint - decimal numeric real - double\ precision serial bigserial + db_numeric_types [ + 'smallint', 'integer', 'bigint', + 'decimal', 'numeric', 'real', + 'double precision', 'serial', 'bigserial' ].to_set.freeze db_type_mapping( - 'uuid' => Types::UUID, + 'uuid' => Types::UUID, 'money' => Types::Money, 'bytea' => Types::Bytea, - 'json' => Types::JSON, + 'json' => Types::JSON, 'jsonb' => Types::JSONB, 'xml' => Types::XML, 'inet' => Types::IPAddress, @@ -39,7 +39,7 @@ class TypeBuilder < Schema::TypeBuilder 'ltree' => Types::LTree ).freeze - db_array_type_matcher '[]'.freeze + db_array_type_matcher '[]' def map_pk_type(type, db_type, **options) if numeric?(type, db_type) diff --git a/lib/rom/sql/extensions/postgres/type_serializer.rb b/lib/rom/sql/extensions/postgres/type_serializer.rb index 8bf6300ea..528470b7d 100644 --- a/lib/rom/sql/extensions/postgres/type_serializer.rb +++ b/lib/rom/sql/extensions/postgres/type_serializer.rb @@ -36,8 +36,8 @@ class TypeSerializer < ROM::SQL::TypeSerializer def call(type) super do - if type.respond_to?(:primitive) && type.primitive.equal?(Array) - "#{ type.meta[:type] }[]" + if type.respond_to?(:primitive) && type.primitive.equal?(::Array) + "#{type.meta[:type]}[]" end end end diff --git a/lib/rom/sql/extensions/postgres/types/geometric.rb b/lib/rom/sql/extensions/postgres/types/geometric.rb index 1690a5f0f..8e2f20a60 100644 --- a/lib/rom/sql/extensions/postgres/types/geometric.rb +++ b/lib/rom/sql/extensions/postgres/types/geometric.rb @@ -37,7 +37,7 @@ module Types Point = Type('point') do SQL::Types.define(Values::Point) do input do |point| - "(#{ point.x },#{ point.y })" + "(#{point.x},#{point.y})" end output do |point| @@ -50,7 +50,7 @@ module Types Line = Type('line') do SQL::Types.define(Values::Line) do input do |line| - "{#{ line.a },#{ line.b },#{line.c}}" + "{#{line.a},#{line.b},#{line.c}}" end output do |line| @@ -63,7 +63,7 @@ module Types Circle = Type('circle') do SQL::Types.define(Values::Circle) do input do |circle| - "<(#{ circle.center.x },#{ circle.center.y }),#{ circle.radius }>" + "<(#{circle.center.x},#{circle.center.y}),#{circle.radius}>" end output do |circle| @@ -77,8 +77,8 @@ module Types Box = Type('box') do SQL::Types.define(Values::Box) do input do |box| - "((#{ box.upper_right.x },#{ box.upper_right.y }),"\ - "(#{ box.lower_left.x },#{ box.lower_left.y }))" + "((#{box.upper_right.x},#{box.upper_right.y})," \ + "(#{box.lower_left.x},#{box.lower_left.y}))" end output do |box| @@ -93,8 +93,8 @@ module Types LineSegment = Type('lseg') do SQL::Types.define(Values::LineSegment) do input do |segment| - "[(#{ segment.begin.x },#{ segment.begin.y }),"\ - "(#{ segment.end.x },#{ segment.end.y })]" + "[(#{segment.begin.x},#{segment.begin.y})," \ + "(#{segment.end.x},#{segment.end.y})]" end output do |segment| @@ -109,8 +109,8 @@ module Types Polygon = Type('polygon') do SQL::Types.define(::Array) do input do |points| - points_joined = points.map { |p| "(#{ p.x },#{ p.y })" }.join(',') - "(#{ points_joined })" + points_joined = points.map { |p| "(#{p.x},#{p.y})" }.join(',') + "(#{points_joined})" end output do |polygon| @@ -123,12 +123,12 @@ module Types Path = Type('path') do SQL::Types.define(Values::Path) do input do |path| - points_joined = path.to_a.map { |p| "(#{ p.x },#{ p.y })" }.join(',') + points_joined = path.to_a.map { |p| "(#{p.x},#{p.y})" }.join(',') if path.open? - "[#{ points_joined }]" + "[#{points_joined}]" else - "(#{ points_joined })" + "(#{points_joined})" end end diff --git a/lib/rom/sql/extensions/postgres/types/ltree.rb b/lib/rom/sql/extensions/postgres/types/ltree.rb index 4ccdfd6a3..a63af6426 100644 --- a/lib/rom/sql/extensions/postgres/types/ltree.rb +++ b/lib/rom/sql/extensions/postgres/types/ltree.rb @@ -234,12 +234,16 @@ module LTreeMethods MATCH_ANY_LTEXTQUERY = ['(', ' ?@ ', ')'].freeze def match(_type, expr, query) - Attribute[SQL::Types::Bool].meta(sql_expr: Sequel::SQL::BooleanExpression.new(:'~', expr, query)) + Attribute[SQL::Types::Bool].meta( + sql_expr: ::Sequel::SQL::BooleanExpression.new(:~, expr, query) + ) end def match_any(_type, expr, query) array = build_array_query(query) - Attribute[SQL::Types::Bool].meta(sql_expr: custom_operator_expr(MATCH_ANY, expr, array)) + Attribute[SQL::Types::Bool].meta( + sql_expr: custom_operator_expr(MATCH_ANY, expr, array) + ) end private @@ -262,31 +266,57 @@ def build_array_query(query, array_type = 'lquery') include LTreeMethods def contain_any_ltextquery(_type, expr, query) - Attribute[SQL::Types::Bool].meta(sql_expr: custom_operator_expr(LTreeMethods::MATCH_LTEXTQUERY, expr, query)) + Attribute[SQL::Types::Bool].meta( + sql_expr: custom_operator_expr( + LTreeMethods::MATCH_LTEXTQUERY, expr, query + ) + ) end def contain_ancestor(_type, expr, query) - Attribute[SQL::Types::Bool].meta(sql_expr: custom_operator_expr(LTreeMethods::ASCENDANT, expr, query)) + Attribute[SQL::Types::Bool].meta( + sql_expr: custom_operator_expr( + LTreeMethods::ASCENDANT, expr, query + ) + ) end def contain_descendant(_type, expr, query) - Attribute[SQL::Types::Bool].meta(sql_expr: custom_operator_expr(LTreeMethods::DESCENDANT, expr, query)) + Attribute[SQL::Types::Bool].meta( + sql_expr: custom_operator_expr( + LTreeMethods::DESCENDANT, expr, query + ) + ) end def find_ancestor(_type, expr, query) - Attribute[LTree].meta(sql_expr: custom_operator_expr(LTreeMethods::FIND_ASCENDANT, expr, query)) + Attribute[LTree].meta( + sql_expr: custom_operator_expr( + LTreeMethods::FIND_ASCENDANT, expr, query + ) + ) end def find_descendant(_type, expr, query) - Attribute[LTree].meta(sql_expr: custom_operator_expr(LTreeMethods::FIND_DESCENDANT, expr, query)) + Attribute[LTree].meta( + sql_expr: custom_operator_expr( + LTreeMethods::FIND_DESCENDANT, expr, query + ) + ) end def match_any_lquery(_type, expr, query) - Attribute[LTree].meta(sql_expr: custom_operator_expr(LTreeMethods::MATCH_ANY_LQUERY, expr, query)) + Attribute[LTree].meta( + sql_expr: custom_operator_expr( + LTreeMethods::MATCH_ANY_LQUERY, expr, query + ) + ) end def match_any_ltextquery(_type, expr, query) - Attribute[LTree].meta(sql_expr: custom_operator_expr(LTreeMethods::MATCH_ANY_LTEXTQUERY, expr, query)) + Attribute[LTree].meta(sql_expr: custom_operator_expr( + LTreeMethods::MATCH_ANY_LTEXTQUERY, expr, query + )) end end @@ -294,35 +324,50 @@ def match_any_ltextquery(_type, expr, query) include LTreeMethods def match_ltextquery(_type, expr, query) - Attribute[SQL::Types::Bool].meta(sql_expr: custom_operator_expr(LTreeMethods::MATCH_LTEXTQUERY, expr, query)) + Attribute[SQL::Types::Bool].meta(sql_expr: custom_operator_expr( + LTreeMethods::MATCH_LTEXTQUERY, expr, query + )) end def contain_descendant(_type, expr, query) array = build_array_query(query, 'ltree') - Attribute[SQL::Types::Bool].meta(sql_expr: custom_operator_expr(LTreeMethods::DESCENDANT, expr, array)) + Attribute[SQL::Types::Bool].meta(sql_expr: custom_operator_expr( + LTreeMethods::DESCENDANT, expr, array + )) end def descendant(_type, expr, query) - Attribute[SQL::Types::Bool].meta(sql_expr: custom_operator_expr(LTreeMethods::DESCENDANT, expr, query)) + Attribute[SQL::Types::Bool].meta(sql_expr: custom_operator_expr( + LTreeMethods::DESCENDANT, expr, query + )) end def contain_ascendant(_type, expr, query) array = build_array_query(query, 'ltree') - Attribute[SQL::Types::Bool].meta(sql_expr: custom_operator_expr(LTreeMethods::ASCENDANT, expr, array)) + Attribute[SQL::Types::Bool].meta(sql_expr: custom_operator_expr( + LTreeMethods::ASCENDANT, expr, array + )) end def ascendant(_type, expr, query) - Attribute[SQL::Types::Bool].meta(sql_expr: custom_operator_expr(LTreeMethods::ASCENDANT, expr, query)) + Attribute[SQL::Types::Bool].meta(sql_expr: custom_operator_expr( + LTreeMethods::ASCENDANT, expr, query + )) end def +(_type, expr, other) - other_value = case other - when ROM::Types::Values::TreePath - other - else - ROM::Types::Values::TreePath.new(other) - end - Attribute[LTree].meta(sql_expr: Sequel::SQL::StringExpression.new(:'||', expr, other_value.to_s)) + other_value = + case other + when ::ROM::Types::Values::TreePath + other + else + ::ROM::Types::Values::TreePath.new(other) + end + Attribute[LTree].meta( + sql_expr: ::Sequel::SQL::StringExpression.new( + :'||', expr, other_value.to_s + ) + ) end end end diff --git a/lib/rom/sql/extensions/postgres/types/range.rb b/lib/rom/sql/extensions/postgres/types/range.rb index 4dfea0b91..b821fe04d 100644 --- a/lib/rom/sql/extensions/postgres/types/range.rb +++ b/lib/rom/sql/extensions/postgres/types/range.rb @@ -9,8 +9,8 @@ module SQL module Postgres module Values Range = ::Struct.new(:lower, :upper, :bounds) do - PAREN_LEFT = '('.freeze - PAREN_RIGHT = ')'.freeze + PAREN_LEFT = '(' + PAREN_RIGHT = ')' def initialize(lower, upper, bounds = :'[)') super @@ -38,10 +38,10 @@ module Types int8range: Sequel::Postgres::PGRange::Parser.new( 'int8range', SQL::Types::Coercible::Integer ), - numrange: Sequel::Postgres::PGRange::Parser.new( + numrange: Sequel::Postgres::PGRange::Parser.new( 'numrange', SQL::Types::Coercible::Integer ), - tsrange: Sequel::Postgres::PGRange::Parser.new( + tsrange: Sequel::Postgres::PGRange::Parser.new( 'tsrange', ::Time.method(:parse) ), tstzrange: Sequel::Postgres::PGRange::Parser.new( diff --git a/lib/rom/sql/extensions/rails_log_subscriber.rb b/lib/rom/sql/extensions/rails_log_subscriber.rb index c94e0c8e9..d6a99d76d 100644 --- a/lib/rom/sql/extensions/rails_log_subscriber.rb +++ b/lib/rom/sql/extensions/rails_log_subscriber.rb @@ -7,15 +7,15 @@ module SQL class RailsLogSubscriber < ActiveSupport::LogSubscriber as_version = begin - require "active_support/gem_version" + require 'active_support/gem_version' ActiveSupport.gem_version rescue LoadError nil end COLOR_OPTION = - if as_version && as_version >= Gem::Version.new("7.2") - {color: true} + if as_version && as_version >= ::Gem::Version.new('7.2') + { color: true } else true end diff --git a/lib/rom/sql/gateway.rb b/lib/rom/sql/gateway.rb index c3313c87b..79497585b 100644 --- a/lib/rom/sql/gateway.rb +++ b/lib/rom/sql/gateway.rb @@ -81,7 +81,7 @@ class Gateway < ROM::Gateway def initialize(uri, options = EMPTY_HASH) @connection = connect(uri, options) load_extensions(Array(options[:extensions])) - Notifications.trigger("configuration.gateway.connected", connection: @connection) + Notifications.trigger('configuration.gateway.connected', connection: @connection) @options = options @@ -152,15 +152,15 @@ def dataset?(name) # Create a table using the configured connection # # @api public - def create_table(*args, &block) - connection.create_table(*args, &block) + def create_table(...) + connection.create_table(...) end # Drops a table # # @api public - def drop_table(*args, &block) - connection.drop_table(*args, &block) + def drop_table(...) + connection.drop_table(...) end # Returns a list of datasets inferred from table names @@ -249,5 +249,5 @@ def transaction_runner(_) end end - Configuration.register_event("configuration.gateway.connected") + Configuration.register_event('configuration.gateway.connected') end diff --git a/lib/rom/sql/group_dsl.rb b/lib/rom/sql/group_dsl.rb index bc533890f..b435d108d 100644 --- a/lib/rom/sql/group_dsl.rb +++ b/lib/rom/sql/group_dsl.rb @@ -9,11 +9,11 @@ class GroupDSL < DSL private # @api private - def method_missing(meth, *args, &block) + def method_missing(meth, ...) if schema.key?(meth) schema[meth].canonical else - ::Sequel::VIRTUAL_ROW.__send__(meth.to_s, *args, &block) + ::Sequel::VIRTUAL_ROW.__send__(meth.to_s, ...) end end end diff --git a/lib/rom/sql/migration.rb b/lib/rom/sql/migration.rb index d082c0cea..15a4dddc5 100644 --- a/lib/rom/sql/migration.rb +++ b/lib/rom/sql/migration.rb @@ -121,8 +121,8 @@ def pending_migrations? # @see ROM::SQL.migration # # @api public - def migration(&block) - migrator.migration(&block) + def migration(&) + migrator.migration(&) end # Run migrations diff --git a/lib/rom/sql/migration/inline_runner.rb b/lib/rom/sql/migration/inline_runner.rb index 7433b6eab..7a17d8556 100644 --- a/lib/rom/sql/migration/inline_runner.rb +++ b/lib/rom/sql/migration/inline_runner.rb @@ -13,8 +13,8 @@ def migration yield(connection) end - def method_missing(m, *args, &block) - connection.public_send(m, *args, &block) + def method_missing(m, ...) + connection.public_send(m, ...) end end end diff --git a/lib/rom/sql/migration/migrator.rb b/lib/rom/sql/migration/migrator.rb index def1bfbc6..bcaae2e94 100644 --- a/lib/rom/sql/migration/migrator.rb +++ b/lib/rom/sql/migration/migrator.rb @@ -16,8 +16,8 @@ module Migration class Migrator extend Initializer - DEFAULT_PATH = 'db/migrate'.freeze - VERSION_FORMAT = '%Y%m%d%H%M%S'.freeze + DEFAULT_PATH = 'db/migrate' + VERSION_FORMAT = '%Y%m%d%H%M%S' DEFAULT_INFERRER = Schema::Inferrer.new.suppress_errors.freeze param :connection @@ -37,14 +37,14 @@ def pending? end # @api private - def migration(&block) - Sequel.migration(&block) + def migration(&) + Sequel.migration(&) end # @api private def create_file(name, version = generate_version, **options) sequence = options[:sequence] ? '%03d' % options[:sequence] : nil - filename = "#{ version }#{ sequence }_#{ name }.rb" + filename = "#{version}#{sequence}_#{name}.rb" content = options[:content] || migration_file_content path = options[:path] || self.path dirname = Pathname(path) diff --git a/lib/rom/sql/migration/schema_diff.rb b/lib/rom/sql/migration/schema_diff.rb index 28a562d83..997f74c18 100644 --- a/lib/rom/sql/migration/schema_diff.rb +++ b/lib/rom/sql/migration/schema_diff.rb @@ -46,7 +46,6 @@ class TableCreated < TableDiff end class TableAltered < TableDiff - option :attribute_changes, default: -> { EMPTY_ARRAY } option :index_changes, default: -> { EMPTY_ARRAY } @@ -135,10 +134,10 @@ def name class IndexAdded < IndexDiff def options options = {} - options[:name] = index.name if !index.name.nil? + options[:name] = index.name unless index.name.nil? options[:unique] = true if index.unique? - options[:type] = index.type if !index.type.nil? - options[:where] = index.predicate if !index.predicate.nil? + options[:type] = index.type unless index.type.nil? + options[:where] = index.predicate unless index.predicate.nil? options end end @@ -146,7 +145,7 @@ def options class IndexRemoved < IndexDiff def options options = {} - options[:name] = index.name if !index.name.nil? + options[:name] = index.name unless index.name.nil? options end end diff --git a/lib/rom/sql/migration/writer.rb b/lib/rom/sql/migration/writer.rb index b0a547481..e3f995ddd 100644 --- a/lib/rom/sql/migration/writer.rb +++ b/lib/rom/sql/migration/writer.rb @@ -7,8 +7,8 @@ module SQL module Migration # @api private class Writer - MIGRATION_BEGIN = "ROM::SQL.migration do\n change do".freeze - MIGRATION_END = "\n end\nend\n".freeze + MIGRATION_BEGIN = "ROM::SQL.migration do\n change do" + MIGRATION_END = "\n end\nend\n" attr_reader :yield_migration @@ -36,11 +36,11 @@ def write(operations, buffer, indent) buffer << indent << op.to_s << ' ' write_arguments(buffer, args) - if !nested.empty? - buffer << ' do' - write(nested, buffer, indent + ' ') - buffer << indent << 'end' - end + next if nested.empty? + + buffer << ' do' + write(nested, buffer, indent + ' ') + buffer << indent << 'end' end end @@ -61,7 +61,7 @@ def migration_name(op) create_or_alter, args = op table_name = args[0] - "#{create_or_alter.to_s.sub('_table', '')}_#{table_name}" + "#{create_or_alter.to_s.sub("_table", "")}_#{table_name}" end end end diff --git a/lib/rom/sql/order_dsl.rb b/lib/rom/sql/order_dsl.rb index e27d06da5..9b62b6913 100644 --- a/lib/rom/sql/order_dsl.rb +++ b/lib/rom/sql/order_dsl.rb @@ -9,11 +9,11 @@ class OrderDSL < DSL private # @api private - def method_missing(meth, *args, &block) + def method_missing(meth, ...) if schema.key?(meth) schema[meth] else - ::Sequel::VIRTUAL_ROW.__send__(meth.to_s.upcase, *args, &block) + ::Sequel::VIRTUAL_ROW.__send__(meth.to_s.upcase, ...) end end end diff --git a/lib/rom/sql/plugin/associates.rb b/lib/rom/sql/plugin/associates.rb index 5d9b1473b..7f906caa7 100644 --- a/lib/rom/sql/plugin/associates.rb +++ b/lib/rom/sql/plugin/associates.rb @@ -10,7 +10,11 @@ module Plugin # @api private module Associates class AssociateOptions - attr_reader :name, :assoc, :opts + attr_reader :name + + attr_reader :assoc + + attr_reader :opts # @api private def initialize(name, relation, opts) @@ -37,7 +41,7 @@ def self.included(klass) defines :associations - associations Hash.new + associations({}) option :associations, default: -> { self.class.associations } option :configured_associations, default: -> { EMPTY_ARRAY } @@ -57,16 +61,17 @@ def build(relation, **options) associate_options = command.associations.map { |(name, opts)| next if configured_assocs.include?(name) + AssociateOptions.new(name, relation, opts) }.compact before_hooks = associate_options.reject(&:after?).map(&:to_hash) after_hooks = associate_options.select(&:after?).map(&:to_hash) - command. - with(configured_associations: configured_assocs + associate_options.map(&:name)). - before(*before_hooks). - after(*after_hooks) + command + .with(configured_associations: configured_assocs + associate_options.map(&:name)) + .before(*before_hooks) + .after(*after_hooks) end # Set command to associate tuples with a parent tuple using provided keys diff --git a/lib/rom/sql/plugin/pagination.rb b/lib/rom/sql/plugin/pagination.rb index 948c436ba..64cbfd013 100644 --- a/lib/rom/sql/plugin/pagination.rb +++ b/lib/rom/sql/plugin/pagination.rb @@ -100,7 +100,7 @@ def at(dataset, current_page, per_page = self.per_page) per_page = per_page.to_i self.class.new( - dataset.offset((current_page-1)*per_page).limit(per_page), + dataset.offset((current_page - 1) * per_page).limit(per_page), current_page: current_page, per_page: per_page ) end diff --git a/lib/rom/sql/projection_dsl.rb b/lib/rom/sql/projection_dsl.rb index a489cd592..682aef3bc 100644 --- a/lib/rom/sql/projection_dsl.rb +++ b/lib/rom/sql/projection_dsl.rb @@ -49,7 +49,7 @@ def respond_to_missing?(name, include_private = false) private # @api private - def method_missing(meth, *args, &block) + def method_missing(meth, *args, &) if schema.key?(meth) schema[meth] else diff --git a/lib/rom/sql/relation.rb b/lib/rom/sql/relation.rb index 45fda701d..029d01f63 100644 --- a/lib/rom/sql/relation.rb +++ b/lib/rom/sql/relation.rb @@ -61,9 +61,9 @@ def self.define_default_views! # @return [SQL::Relation] # # @api public - class_eval <<-RUBY, __FILE__, __LINE__ + 1 - def by_pk(#{schema.primary_key.map(&:name).join(', ')}) - where(#{schema.primary_key.map { |attr| "schema.canonical[:#{attr.name}] => #{attr.name}" }.join(', ')}) + class_eval(<<-RUBY, __FILE__, __LINE__ + 1) + def by_pk(#{schema.primary_key.map(&:name).join(", ")}) + where(#{schema.primary_key.map { |attr| "schema.canonical[:#{attr.name}] => #{attr.name}" }.join(", ")}) end RUBY else @@ -75,7 +75,7 @@ def by_pk(#{schema.primary_key.map(&:name).join(', ')}) # @return [SQL::Relation] # # @api public - class_eval <<-RUBY, __FILE__, __LINE__ + 1 + class_eval(<<-RUBY, __FILE__, __LINE__ + 1) def by_pk(pk) if primary_key.nil? raise MissingPrimaryKeyError.new( @@ -139,8 +139,8 @@ def assoc(name) # @return [Mixed] # # @api public - def transaction(opts = EMPTY_HASH, &block) - Transaction.new(dataset.db).run(opts, &block) + def transaction(opts = EMPTY_HASH, &) + Transaction.new(dataset.db).run(opts, &) end # Return raw column names diff --git a/lib/rom/sql/relation/reading.rb b/lib/rom/sql/relation/reading.rb index 0cadf192e..3ca8ed293 100644 --- a/lib/rom/sql/relation/reading.rb +++ b/lib/rom/sql/relation/reading.rb @@ -11,18 +11,18 @@ class Relation < ROM::Relation # @api public module Reading # Row-level lock modes - ROW_LOCK_MODES = Hash.new({ update: "FOR UPDATE" }).update( + ROW_LOCK_MODES = Hash.new({ update: 'FOR UPDATE' }).update( # https://www.postgresql.org/docs/current/static/sql-select.html#SQL-FOR-UPDATE-SHARE postgres: { - update: 'FOR UPDATE'.freeze, - no_key_update: 'FOR NO KEY UPDATE'.freeze, - share: 'FOR SHARE'.freeze, - key_share: 'FOR KEY SHARE'.freeze + update: 'FOR UPDATE', + no_key_update: 'FOR NO KEY UPDATE', + share: 'FOR SHARE', + key_share: 'FOR KEY SHARE' }, # https://dev.mysql.com/doc/refman/5.7/en/innodb-locking-reads.html mysql: { - update: 'FOR UPDATE'.freeze, - share: 'LOCK IN SHARE MODE'.freeze + update: 'FOR UPDATE', + share: 'LOCK IN SHARE MODE' } ).freeze @@ -140,11 +140,11 @@ def qualified_columns # from tuples # # @api public - def map(key = nil, &block) + def map(key = nil, &) if key - dataset.map(key, &block) + dataset.map(key, &) else - dataset.map(&block) + dataset.map(&) end end @@ -235,8 +235,8 @@ def rename(options) # @return [Relation] # # @api public - def select(*args, &block) - schema.project(*args, &block).(self) + def select(...) + schema.project(...).(self) end alias_method :project, :select @@ -247,8 +247,8 @@ def select(*args, &block) # @return [Relation] # # @api public - def select_append(*args, &block) - schema.merge(schema.canonical.project(*args, &block)).(self) + def select_append(...) + schema.merge(schema.canonical.project(...)).(self) end # Returns a copy of the relation with a SQL DISTINCT clause. @@ -271,8 +271,8 @@ def select_append(*args, &block) # @return [Relation] # # @api public - def distinct(*args, &block) - new(dataset.__send__(__method__, *args, &block)) + def distinct(...) + new(dataset.__send__(__method__, ...)) end # Returns a result of SQL SUM clause. @@ -381,8 +381,8 @@ def where(*args, &block) # @return [Relation] # # @api public - def exclude(*args, &block) - new(dataset.__send__(__method__, *args, &block)) + def exclude(...) + new(dataset.__send__(__method__, ...)) end # Restrict a relation to match grouping criteria @@ -501,8 +501,8 @@ def unordered # @return [Relation] # # @api public - def reverse(*args, &block) - new(dataset.__send__(__method__, *args, &block)) + def reverse(...) + new(dataset.__send__(__method__, ...)) end # Limit a relation to a specific number of tuples @@ -590,8 +590,8 @@ def offset(num) # @return [Relation] # # @api public - def join(*args, &block) - __join__(__method__, *args, &block) + def join(...) + __join__(__method__, ...) end alias_method :inner_join, :join @@ -640,8 +640,8 @@ def join(*args, &block) # @return [Relation] # # @api public - def left_join(*args, &block) - __join__(__method__, *args, &block) + def left_join(...) + __join__(__method__, ...) end # Join with another relation using RIGHT JOIN @@ -689,8 +689,8 @@ def left_join(*args, &block) # @return [Relation] # # @api public - def right_join(*args, &block) - __join__(__method__, *args, &block) + def right_join(...) + __join__(__method__, ...) end # Group by specific columns @@ -784,8 +784,8 @@ def group_append(*args, &block) # @return [Relation] # # @api public - def group_and_count(*args, &block) - new(dataset.__send__(__method__, *args, &block)) + def group_and_count(...) + new(dataset.__send__(__method__, ...)) end # Select and group by specific columns @@ -799,8 +799,8 @@ def group_and_count(*args, &block) # @return [Relation] # # @api public - def select_group(*args, &block) - new_schema = schema.project(*args, &block) + def select_group(...) + new_schema = schema.project(...) new_schema.(self).group(*new_schema) end @@ -814,13 +814,13 @@ def select_group(*args, &block) # # @param [Hash] options Options for union # @option options [Symbol] :alias Use the given value as the #from_self alias - # @option options [TrueClass, FalseClass] :all Set to true to use UNION ALL instead of UNION, so duplicate rows can occur - # @option options [TrueClass, FalseClass] :from_self Set to false to not wrap the returned dataset in a #from_self, use with care. + # @option options [true, false] :all Set to true to use UNION ALL instead of UNION, so duplicate rows can occur + # @option options [true, false] :from_self Set to false to not wrap the returned dataset in a #from_self, use with care. # # @returRelation] # # @api public - def union(relation, options = EMPTY_HASH, &block) + def union(relation, options = EMPTY_HASH, &) # We use the original relation name here if both relations have the # same name. This makes it so if the user at some point references # the relation directly by name later on things won't break in @@ -830,7 +830,7 @@ def union(relation, options = EMPTY_HASH, &block) opts = { alias: alias_name.to_sym, **options } new_schema = schema.qualified(opts[:alias]) - new_schema.(new(dataset.__send__(__method__, relation.dataset, opts, &block))) + new_schema.(new(dataset.__send__(__method__, relation.dataset, opts, &))) end # Checks whether a relation has at least one tuple @@ -848,8 +848,8 @@ def union(relation, options = EMPTY_HASH, &block) # @return [TrueClass, FalseClass] # # @api public - def exist?(*args, &block) - !where(*args, &block).limit(1).count.zero? + def exist?(...) + !where(...).limit(1).count.zero? end # Return if a restricted relation has 0 tuples @@ -1050,7 +1050,7 @@ def lock_clause(mode: :update, skip_locked: false, of: nil, wait: nil) stmt << ' OF ' << Array(of).join(', ') if of if skip_locked - raise ArgumentError, 'SKIP LOCKED cannot be used with (NO)WAIT clause' if !wait.nil? + raise ArgumentError, 'SKIP LOCKED cannot be used with (NO)WAIT clause' unless wait.nil? stmt << ' SKIP LOCKED' else @@ -1111,7 +1111,8 @@ def __join__(type, other, join_cond = EMPTY_HASH, opts = EMPTY_HASH, &block) associations[other.name.key].join(type, self, other) end else - raise ArgumentError, "+other+ must be either a symbol or a relation, #{other.class} given" + raise ArgumentError, + "+other+ must be either a symbol or a relation, #{other.class} given" end end end diff --git a/lib/rom/sql/relation/writing.rb b/lib/rom/sql/relation/writing.rb index 4aec53d5d..8e32f8ca1 100644 --- a/lib/rom/sql/relation/writing.rb +++ b/lib/rom/sql/relation/writing.rb @@ -16,7 +16,7 @@ module Writing # @return [Integer] Number of affected rows # # @api public - def upsert(*args, &block) + def upsert(*args, &) if args.size > 1 && args[-1].is_a?(Hash) *values, opts = args else @@ -24,7 +24,7 @@ def upsert(*args, &block) opts = EMPTY_HASH end - dataset.insert_conflict(opts).insert(*values, &block) + dataset.insert_conflict(opts).insert(*values, &) end # Insert tuple into relation @@ -37,8 +37,8 @@ def upsert(*args, &block) # @return [Hash] Inserted tuple # # @api public - def insert(*args, &block) - dataset.insert(*args, &block) + def insert(...) + dataset.insert(...) end # Multi insert tuples into relation @@ -51,8 +51,8 @@ def insert(*args, &block) # @return [Array] A list of executed SQL statements # # @api public - def multi_insert(*args, &block) - dataset.multi_insert(*args, &block) + def multi_insert(...) + dataset.multi_insert(...) end # Update tuples in the relation @@ -64,8 +64,8 @@ def multi_insert(*args, &block) # @return [Integer] Number of updated rows # # @api public - def update(*args, &block) - dataset.update(*args, &block) + def update(...) + dataset.update(...) end # Delete tuples from the relation @@ -78,8 +78,8 @@ def update(*args, &block) # @return [Integer] Number of deleted tuples # # @api public - def delete(*args, &block) - dataset.delete(*args, &block) + def delete(...) + dataset.delete(...) end # Insert tuples from other relation @@ -119,7 +119,13 @@ def import(other, options = EMPTY_HASH) else columns = other.schema.map { |a| a.alias || a.name } keys = columns.map(&:to_sym) - dataset.import(columns, other.to_a.map { |record| record.to_h.values_at(*keys) }, options) + dataset.import( + columns, + other.to_a.map { |record| + record.to_h.values_at(*keys) + }, + options + ) end end end diff --git a/lib/rom/sql/restriction_dsl.rb b/lib/rom/sql/restriction_dsl.rb index fa80e60e9..b74e8f156 100644 --- a/lib/rom/sql/restriction_dsl.rb +++ b/lib/rom/sql/restriction_dsl.rb @@ -20,7 +20,7 @@ def call(&block) private # @api private - def method_missing(meth, *args, &block) + def method_missing(meth, ...) if schema.key?(meth) schema[meth] else @@ -29,7 +29,7 @@ def method_missing(meth, *args, &block) if type ::ROM::SQL::Function.new(type).meta(schema: schema) else - ::Sequel::VIRTUAL_ROW.__send__(meth, *args, &block) + ::Sequel::VIRTUAL_ROW.__send__(meth, ...) end end end diff --git a/lib/rom/sql/schema.rb b/lib/rom/sql/schema.rb index 7c2da7a98..a05f488e8 100644 --- a/lib/rom/sql/schema.rb +++ b/lib/rom/sql/schema.rb @@ -32,8 +32,8 @@ class Schema < ROM::Schema # @return [Mixed] Result of the block call # # @api public - def restriction(&block) - RestrictionDSL.new(self).call(&block) + def restriction(&) + RestrictionDSL.new(self).call(&) end # Open Order DSL for setting ORDER clause in queries @@ -43,8 +43,8 @@ def restriction(&block) # @return [Mixed] Result of the block call # # @api public - def order(&block) - OrderDSL.new(self).call(&block) + def order(&) + OrderDSL.new(self).call(&) end # Open Group DSL for setting GROUP BY clause in queries @@ -54,8 +54,8 @@ def order(&block) # @return [Mixed] Result of the block call # # @api public - def group(&block) - GroupDSL.new(self).call(&block) + def group(&) + GroupDSL.new(self).call(&) end # Return a new schema with attributes marked as qualified @@ -141,7 +141,7 @@ def joined # # @api public def call(relation) - relation.new(relation.dataset.select(*self.qualified_projection), schema: self) + relation.new(relation.dataset.select(*qualified_projection), schema: self) end # Return an empty schema diff --git a/lib/rom/sql/schema/attributes_inferrer.rb b/lib/rom/sql/schema/attributes_inferrer.rb index ed5f17076..c2060647d 100644 --- a/lib/rom/sql/schema/attributes_inferrer.rb +++ b/lib/rom/sql/schema/attributes_inferrer.rb @@ -12,7 +12,7 @@ class AttributesInferrer defines :type_builders - CONSTRAINT_DB_TYPE = 'add_constraint'.freeze + CONSTRAINT_DB_TYPE = 'add_constraint' option :type_builder diff --git a/lib/rom/sql/schema/dsl.rb b/lib/rom/sql/schema/dsl.rb index e2fc630ef..7dc151bea 100644 --- a/lib/rom/sql/schema/dsl.rb +++ b/lib/rom/sql/schema/dsl.rb @@ -16,8 +16,8 @@ class DSL < ROM::Schema::DSL # Define indexes within a block # # @api public - def indexes(&block) - @index_dsl = IndexDSL.new(**options, &block) + def indexes(&) + @index_dsl = IndexDSL.new(**options, &) end private diff --git a/lib/rom/sql/schema/index_dsl.rb b/lib/rom/sql/schema/index_dsl.rb index a0607cd2f..f0f019002 100644 --- a/lib/rom/sql/schema/index_dsl.rb +++ b/lib/rom/sql/schema/index_dsl.rb @@ -6,7 +6,7 @@ module ROM module SQL class Schema < ROM::Schema # @api public - class IndexDSL # < BasicObject + class IndexDSL extend Initializer option :attr_class @@ -14,12 +14,12 @@ class IndexDSL # < BasicObject attr_reader :registry # @api private - def initialize(*, **, &block) + def initialize(*, **, &) super @registry = [] - instance_exec(&block) + instance_exec(&) end # @api public diff --git a/lib/rom/sql/schema/inferrer.rb b/lib/rom/sql/schema/inferrer.rb index baad0849b..e8195d266 100644 --- a/lib/rom/sql/schema/inferrer.rb +++ b/lib/rom/sql/schema/inferrer.rb @@ -38,8 +38,8 @@ def call(schema, gateway) else infer_from_attributes(gateway, schema, **super) end - rescue Sequel::Error => error - on_error(schema.name, error) + rescue Sequel::Error => e + on_error(schema.name, e) { **FALLBACK_SCHEMA, indexes: schema.indexes } end @@ -49,10 +49,14 @@ def infer_from_database(gateway, schema, attributes:, **rest) indexes = indexes_from_database(gateway, schema, idx) foreign_keys = foreign_keys_from_database(gateway, schema, idx) - { **rest, - attributes: attributes.map { |attr| mark_fk(mark_indexed(attr, indexes), foreign_keys) }, + { + **rest, + attributes: attributes.map { |attr| + mark_fk(mark_indexed(attr, indexes), foreign_keys) + }, foreign_keys: foreign_keys, - indexes: indexes } + indexes: indexes + } end # @api private @@ -60,10 +64,12 @@ def infer_from_attributes(_gateway, schema, attributes:, **rest) indexes = schema.indexes | indexes_from_attributes(attributes) foreign_keys = foreign_keys_from_attributes(attributes) - { **rest, + { + **rest, attributes: attributes.map { |attr| mark_indexed(attr, indexes) }, foreign_keys: foreign_keys, - indexes: indexes } + indexes: indexes + } end # @api private @@ -96,18 +102,16 @@ def foreign_keys_from_database(gateway, schema, attributes) # @api private def indexes_from_attributes(attributes) - attributes. - select(&:indexed?). - map { |attr| SQL::Index.new([attr.unwrap]) }. - to_set + attributes + .select(&:indexed?) + .to_set { |attr| SQL::Index.new([attr.unwrap]) } end # @api private def foreign_keys_from_attributes(attributes) - attributes. - select(&:foreign_key?). - map { |attr| SQL::ForeignKey.new([attr.unwrap], attr.target) }. - to_set + attributes + .select(&:foreign_key?) + .to_set { |attr| SQL::ForeignKey.new([attr.unwrap], attr.target) } end # @api private diff --git a/lib/rom/sql/schema/type_builder.rb b/lib/rom/sql/schema/type_builder.rb index 09eb9ad74..b644731ff 100644 --- a/lib/rom/sql/schema/type_builder.rb +++ b/lib/rom/sql/schema/type_builder.rb @@ -21,7 +21,7 @@ def self.[](db_type) defines :ruby_type_mapping, :numeric_pk_type - DECIMAL_REGEX = /(?:decimal|numeric)\((\d+)(?:,\s*(\d+))?\)/.freeze + DECIMAL_REGEX = /(?:decimal|numeric)\((\d+)(?:,\s*(\d+))?\)/ ruby_type_mapping( integer: Types::Integer, @@ -70,7 +70,7 @@ def map_pk_type(_ruby_type, _db_type, **) def map_type(ruby_type, db_type, **kw) type = self.class.ruby_type_mapping[ruby_type || guess_type(db_type)] - if db_type.is_a?(String) && db_type.include?('numeric') || db_type.include?('decimal') + if (db_type.is_a?(String) && db_type.include?('numeric')) || db_type.include?('decimal') map_decimal_type(db_type) elsif db_type.is_a?(String) && db_type.include?('char') && kw[:max_length] type.meta(limit: kw[:max_length]) diff --git a/lib/rom/sql/tasks/migration_tasks.rake b/lib/rom/sql/tasks/migration_tasks.rake index 54dabb4c2..27df12477 100644 --- a/lib/rom/sql/tasks/migration_tasks.rake +++ b/lib/rom/sql/tasks/migration_tasks.rake @@ -13,8 +13,8 @@ module ROM gateway.run_migrations(migration_options.merge(options)) end - def create_migration(*args) - gateway.migrator.create_file(*args) + def create_migration(...) + gateway.migrator.create_file(...) end # Global environment used for running migrations. You normally @@ -24,8 +24,7 @@ module ROM # @api public attr_accessor :env - - # Migration options, which are passed to `ROM::SQL::RakeSupport.run_migrations`. You can + # Migration options, which are passed to `ROM::SQL::RakeSupport.run_migrations`. You can # set them in the `db:setup` task with `ROM::SQL::RakeSupport.migration_options = { ... }` # # @api public @@ -84,7 +83,7 @@ namespace :db do end desc 'Create a migration (parameters: NAME, VERSION)' - task :create_migration, [:name, :version] => :rom_configuration do |_, args| + task :create_migration, %i[name version] => :rom_configuration do |_, args| name, version = args.values_at(:name, :version) if name.nil? diff --git a/lib/rom/sql/type_dsl.rb b/lib/rom/sql/type_dsl.rb index 7a1e3b830..04fb5e72e 100644 --- a/lib/rom/sql/type_dsl.rb +++ b/lib/rom/sql/type_dsl.rb @@ -6,7 +6,11 @@ module SQL # # @api public class TypeDSL - attr_reader :definition, :input_constructor, :output_constructor + attr_reader :definition + + attr_reader :input_constructor + + attr_reader :output_constructor # @api private def initialize(value_type) @@ -18,8 +22,8 @@ def initialize(value_type) end # @api private - def call(&block) - instance_exec(&block) + def call(&) + instance_exec(&) definition.constructor(input_constructor) .meta(read: definition.constructor(output_constructor)) diff --git a/lib/rom/sql/type_extensions.rb b/lib/rom/sql/type_extensions.rb index 09898d464..fa9a97a79 100644 --- a/lib/rom/sql/type_extensions.rb +++ b/lib/rom/sql/type_extensions.rb @@ -30,13 +30,13 @@ def [](type) # @param [Dry::Types::Type] type Type # # @api public - def register(type, &block) + def register(type, &) extensions = @types[type.meta[:database]] db_type = type.meta[:db_type] - mod = Module.new(&block) - ctx = Object.new.extend(mod) - functions = mod.public_instance_methods.each_with_object({}) { |m, ms| ms[m] = ctx.method(m) } + mod = ::Module.new(&) + ctx = ::Object.new.extend(mod) + functions = mod.public_instance_methods.to_h { |m| [m, ctx.method(m)] } extensions[db_type] = (extensions[db_type] || {}).merge(functions) end end diff --git a/lib/rom/sql/type_serializer.rb b/lib/rom/sql/type_serializer.rb index 508dc0554..b43c1c776 100644 --- a/lib/rom/sql/type_serializer.rb +++ b/lib/rom/sql/type_serializer.rb @@ -29,7 +29,7 @@ def self.[](db_type) Types::Date => 'date', Types::Bool => 'boolean', Types::Decimal => 'numeric', - Types::Float => 'float', + Types::Float => 'float' ) def call(type) @@ -40,7 +40,7 @@ def call(type) self.class.mapping.fetch(type.with(meta: meta)) { if block_given? yield(type) - end or raise "Cannot serialize #{ type }" + end or raise "Cannot serialize #{type}" } end end diff --git a/lib/rom/sql/types.rb b/lib/rom/sql/types.rb index e650409f0..51cf0b738 100644 --- a/lib/rom/sql/types.rb +++ b/lib/rom/sql/types.rb @@ -37,8 +37,8 @@ def self.ForeignKey(relation, type = Types::Integer.meta(index: true)) # @return [Dry::Types::Nominal] # # @api public - def self.define(value_type, &block) - TypeDSL.new(value_type).call(&block) + def self.define(value_type, &) + TypeDSL.new(value_type).call(&) end Serial = Integer.meta(primary_key: true) diff --git a/lib/rom/sql/version.rb b/lib/rom/sql/version.rb index 9173d5987..72c721e17 100644 --- a/lib/rom/sql/version.rb +++ b/lib/rom/sql/version.rb @@ -2,6 +2,6 @@ module ROM module SQL - VERSION = "3.7.0" + VERSION = '3.7.0' end end diff --git a/lib/rom/types/values.rb b/lib/rom/types/values.rb index deed7e19b..2b122efe6 100644 --- a/lib/rom/types/values.rb +++ b/lib/rom/types/values.rb @@ -6,7 +6,7 @@ module ROM module Types module Values class TreePath < ::Struct.new(:value, :separator) - DEFAULT_SEPARATOR = '.'.freeze + DEFAULT_SEPARATOR = '.' # @api public def self.new(value, separator = DEFAULT_SEPARATOR) diff --git a/spec/extensions/postgres/attribute/array_spec.rb b/spec/extensions/postgres/attribute/array_spec.rb index 2ee947b29..3f15237c9 100644 --- a/spec/extensions/postgres/attribute/array_spec.rb +++ b/spec/extensions/postgres/attribute/array_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + RSpec.describe 'ROM::SQL::Attribute / PG array', :postgres do subject(:relation) { relations[:pg_arrays] } diff --git a/spec/extensions/postgres/attribute/range_spec.rb b/spec/extensions/postgres/attribute/range_spec.rb index 0b04559c8..937532e96 100644 --- a/spec/extensions/postgres/attribute/range_spec.rb +++ b/spec/extensions/postgres/attribute/range_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + RSpec.describe 'ROM::SQL::Attribute', :postgres do include_context 'database setup' @@ -115,7 +117,7 @@ def create_ranges_table(db_type, values) let(:values) do { - containing: range_value.new(3, 9, :'[]'), + containing: range_value.new(3, 9, :[]), contained: range_value.new(5, 7, :'[)'), empty: range_value.new(0, 0, :'()'), left: range_value.new(nil, 3, :'(]'), @@ -136,7 +138,7 @@ def create_ranges_table(db_type, values) containing: range_value.new( Time.parse('2017-09-25 03:00:00'), Time.parse('2017-09-25 09:00:00'), - :'[]' + :[] ), contained: range_value.new( Time.parse('2017-09-25 05:00:00'), @@ -165,7 +167,7 @@ def create_ranges_table(db_type, values) containing: range_value.new( Date.parse('2017-10-03'), Date.parse('2017-10-09'), - :'[]' + :[] ), contained: range_value.new( Date.parse('2017-10-05'), diff --git a/spec/extensions/postgres/attribute_spec.rb b/spec/extensions/postgres/attribute_spec.rb index 4e1de701f..6f1f8f653 100644 --- a/spec/extensions/postgres/attribute_spec.rb +++ b/spec/extensions/postgres/attribute_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + RSpec.describe 'ROM::SQL::Attribute', :postgres do include_context 'database setup' @@ -13,8 +15,8 @@ let(:people) { relations[:people] } let(:create_person) { commands[:people].create } - %i(json jsonb).each do |type| - describe "using arrays in #{ type }" do + %i[json jsonb].each do |type| + describe "using arrays in #{type}" do before do conn.create_table :pg_people do primary_key :id @@ -27,104 +29,132 @@ define(:update) end - create_person.(name: 'John Doe', fields: [{ name: 'age', value: '30' }, - { name: 'height', value: 180 }]) - create_person.(name: 'Jade Doe', fields: [{ name: 'age', value: '25' }]) + create_person.( + name: 'John Doe', + fields: [ + { name: 'age', value: '30' }, + { name: 'height', value: 180 } + ] + ) + create_person.( + name: 'Jade Doe', fields: [{ name: 'age', value: '25' }] + ) end it 'fetches data from jsonb array by index' do - expect(people.select { [fields.get(1).as(:field)] }.where(name: 'John Doe').one). - to eql(field: { 'name' => 'height', 'value' => 180 }) + expect( + people.select { [fields.get(1).as(:field)] }.where(name: 'John Doe').one + ).to eql(field: { 'name' => 'height', 'value' => 180 }) end it 'fetches data from jsonb array' do - expect(people.select { fields.get(1).get_text('value').as(:height) }.where(name: 'John Doe').one). - to eql(height: '180') + expect( + people.select { fields.get(1).get_text('value').as(:height) }.where(name: 'John Doe').one + ).to eql(height: '180') end it 'fetches data with path' do - expect(people.select(people[:fields].get_text('1', 'value').as(:height)).to_a). - to eql([{ height: '180' }, { height: nil }]) + expect( + people.select(people[:fields].get_text('1', 'value').as(:height)).to_a + ).to eql([{ height: '180' }, { height: nil }]) end if type == :jsonb it 'allows to query jsonb by inclusion' do - expect(people.select(:name).where { fields.contain([value: '30']) }.one). - to eql(name: 'John Doe') + expect( + people.select(:name).where { fields.contain([value: '30']) }.one + ).to eql(name: 'John Doe') end it 'cat project result of contains' do - expect(people.select { fields.contain([value: '30']).as(:contains) }.to_a). - to eql([{ contains: true }, { contains: false }]) + expect( + people.select { fields.contain([value: '30']).as(:contains) }.to_a + ).to eql([{ contains: true }, { contains: false }]) end it 'deletes key from result' do - expect(people.select { fields.delete(0).as(:result) }.limit(1).one). - to eq(result: ['name' => 'height', 'value' => 180]) + expect( + people.select { fields.delete(0).as(:result) }.limit(1).one + ).to eq(result: ['name' => 'height', 'value' => 180]) end it 'deletes by path' do - expect(people.select { fields.delete('0', 'name').delete('1', 'name').as(:result) }.limit(1).one). - to eq(result: [{ 'value' => '30' }, { 'value' => 180 }]) + expect( + people.select { fields.delete('0', 'name').delete('1', 'name').as(:result) }.limit(1).one + ).to eq(result: [{ 'value' => '30' }, { 'value' => 180 }]) end it 'concatenates JSON values' do - expect(people.select { (fields + [name: 'height', value: 165]).as(:result) }.by_pk(2).one). - to eq(result: [{ 'name' => 'age', 'value' => '25' }, - { 'name' => 'height', 'value' => 165 }]) + expect( + people.select { (fields + [name: 'height', value: 165]).as(:result) }.by_pk(2).one + ).to eq( + result: [ + { 'name' => 'age', 'value' => '25' }, + { 'name' => 'height', 'value' => 165 } + ] + ) end end end - if type == :jsonb - describe "using maps in #{ type }" do - before do - conn.create_table :pg_people do - primary_key :id - String :name - column :data, type - end - - conf.commands(:people) do - define(:create) - define(:update) - end - - create_person.(name: 'John Doe', data: { age: 30, height: 180 }) - create_person.(name: 'Jade Doe', data: { age: 25 }) - end + next unless type == :jsonb - it 'queries data by inclusion' do - expect(people.select(:name).where { data.contain(age: 30) }.one). - to eql(name: 'John Doe') + describe "using maps in #{type}" do + before do + conn.create_table :pg_people do + primary_key :id + String :name + column :data, type end - it 'queries data by left inclusion' do - expect(people.select(:name).where { data.contained_by(age: 25, foo: 'bar') }.one). - to eql(name: 'Jade Doe') + conf.commands(:people) do + define(:create) + define(:update) end - it 'checks for key presence' do - expect(people.select { data.has_key('height').as(:there) }.to_a). - to eql([{ there: true }, { there: false }]) + create_person.(name: 'John Doe', data: { age: 30, height: 180 }) + create_person.(name: 'Jade Doe', data: { age: 25 }) + end - expect(people.select(:name).where { data.has_any_key('height', 'width') }.one). - to eql(name: 'John Doe') + it 'queries data by inclusion' do + expect( + people.select(:name).where { data.contain(age: 30) }.one + ).to eql(name: 'John Doe') + end - expect(people.select(:name).where { data.has_all_keys('height', 'age') }.one). - to eql(name: 'John Doe') - end + it 'queries data by left inclusion' do + expect( + people.select(:name).where { data.contained_by(age: 25, foo: 'bar') }.one + ).to eql(name: 'Jade Doe') + end - it 'concatenates JSON values' do - expect(people.select { data.merge(height: 165).as(:result) }.by_pk(2).one). - to eql(result: { 'age' => 25, 'height' => 165 }) - end + it 'checks for key presence' do + expect( + people.select { data.has_key('height').as(:there) }.to_a + ).to eql([{ there: true }, { there: false }]) - it 'deletes key from result' do - expect(people.select { data.delete('height').as(:result) }.to_a). - to eql([{ result: { 'age' => 30 } }, - { result: { 'age' => 25 } }]) - end + expect( + people.select(:name).where { data.has_any_key('height', 'width') }.one + ).to eql(name: 'John Doe') + + expect( + people.select(:name).where { data.has_all_keys('height', 'age') }.one + ).to eql(name: 'John Doe') + end + + it 'concatenates JSON values' do + expect( + people.select { data.merge(height: 165).as(:result) }.by_pk(2).one + ).to eql(result: { 'age' => 25, 'height' => 165 }) + end + + it 'deletes key from result' do + expect( + people.select { data.delete('height').as(:result) }.to_a + ).to eql([ + { result: { 'age' => 30 } }, + { result: { 'age' => 25 } } + ]) end end end @@ -143,66 +173,82 @@ define(:update) end - create_person.(name: 'John Doe', emails: %w(john@doe.com john@example.com), bigids: [84]) - create_person.(name: 'Jade Doe', emails: %w(jade@hotmail.com), bigids: [42]) + create_person.(name: 'John Doe', emails: %w[john@doe.com john@example.com], bigids: [84]) + create_person.(name: 'Jade Doe', emails: %w[jade@hotmail.com], bigids: [42]) end it 'filters by email inclusion' do - expect(people.select(:name).where { emails.contain(['john@doe.com']) }.one). - to eql(name: 'John Doe') + expect( + people.select(:name).where { emails.contain(%w[john@doe.com]) }.one + ).to eql(name: 'John Doe') end it 'coerces values so that PG does not complain' do - expect(people.select(:name).where { bigids.contain([84]) }.one). - to eql(name: 'John Doe') + expect( + people.select(:name).where { bigids.contain([84]) }.one + ).to eql(name: 'John Doe') end it 'fetches element by index' do - expect(people.select { [name, emails.get(2).as(:second_email)] }.to_a). - to eql([{ name: 'John Doe', second_email: 'john@example.com' }, - { name: 'Jade Doe', second_email: nil }]) + expect( + people.select { [name, emails.get(2).as(:second_email)] }.to_a + ).to eql([ + { name: 'John Doe', second_email: 'john@example.com' }, + { name: 'Jade Doe', second_email: nil } + ]) end it 'restricts with ANY' do - expect(people.select(:name).where { bigids.any(84)}.one). - to eql(name: 'John Doe') + expect( + people.select(:name).where { bigids.any(84) }.one + ).to eql(name: 'John Doe') end it 'restricts by <@' do - expect(people.select(:name).where { bigids.contained_by((30..50).to_a) }.one). - to eql(name: 'Jade Doe') + expect( + people.select(:name).where { bigids.contained_by((30..50).to_a) }.one + ).to eql(name: 'Jade Doe') end it 'returns array length' do - expect(people.select { [name, emails.length.as(:size)] }.to_a). - to eql([{ name: 'John Doe', size: 2 }, { name: 'Jade Doe', size: 1 }]) + expect( + people.select { [name, emails.length.as(:size)] }.to_a + ).to eql([{ name: 'John Doe', size: 2 }, { name: 'Jade Doe', size: 1 }]) end it 'restrict by overlapping with other array' do - expect(people.select(:name).where { emails.overlaps(%w(jade@hotmail.com)) }.one). - to eql(name: 'Jade Doe') + expect( + people.select(:name).where { emails.overlaps(%w[jade@hotmail.com]) }.one + ).to eql(name: 'Jade Doe') - expect(people.select(:name).where { bigids.overlaps([42]) }.one). - to eql(name: 'Jade Doe') + expect( + people.select(:name).where { bigids.overlaps([42]) }.one + ).to eql(name: 'Jade Doe') end it 'removes element by value' do - expect(people.select { emails.remove_value('john@example.com').as(:emails) }.to_a). - to eq([{ emails: %w(john@doe.com) }, { emails: %w(jade@hotmail.com) }]) + expect( + people.select { emails.remove_value('john@example.com').as(:emails) }.to_a + ).to eq([{ emails: %w[john@doe.com] }, { emails: %w[jade@hotmail.com] }]) - expect(people.select(:name).where { bigids.remove_value(100).contain([42]) }.one). - to eql(name: 'Jade Doe') + expect( + people.select(:name).where { bigids.remove_value(100).contain([42]) }.one + ).to eql(name: 'Jade Doe') end it 'joins values' do - expect(people.select { emails.join(',').as(:emails) }.to_a). - to eql([{ emails: 'john@doe.com,john@example.com' }, - { emails: 'jade@hotmail.com' }]) + expect( + people.select { emails.join(',').as(:emails) }.to_a + ).to eql([ + { emails: 'john@doe.com,john@example.com' }, + { emails: 'jade@hotmail.com' } + ]) end it 'concatenates arrays' do - expect(people.select { (emails + %w(foo@bar.com)).as(:emails) }.where { name.is('Jade Doe') }.one). - to eq(emails: %w(jade@hotmail.com foo@bar.com)) + expect( + people.select { (emails + %w[foo@bar.com]).as(:emails) }.where { name.is('Jade Doe') }.one + ).to eq(emails: %w[jade@hotmail.com foo@bar.com]) end end @@ -222,11 +268,11 @@ define(:update) end - create_person.(name: 'John Wilkson',ltree_tags: ltree('Bottom'), parents_tags: [ltree('Top'), ltree('Top.Building')]) - create_person.(name: 'John Wayne',ltree_tags: ltree('Bottom.Countries'), parents_tags: [ltree('Left'), ltree('Left.Parks')]) - create_person.(name: 'John Fake',ltree_tags: ltree('Bottom.Cities'), parents_tags: [ltree('Top.Building.EmpireState'), ltree('Top.Building.EmpireState.381')]) - create_person.(name: 'John Bros',ltree_tags: ltree('Bottom.Cities.Melbourne'), parents_tags: [ltree('Right.Cars.Ford'), ltree('Right.Cars.Nissan')]) - create_person.(name: 'John Wick',ltree_tags: ltree('Bottom.Countries.Australia')) + create_person.(name: 'John Wilkson', ltree_tags: ltree('Bottom'), parents_tags: [ltree('Top'), ltree('Top.Building')]) + create_person.(name: 'John Wayne', ltree_tags: ltree('Bottom.Countries'), parents_tags: [ltree('Left'), ltree('Left.Parks')]) + create_person.(name: 'John Fake', ltree_tags: ltree('Bottom.Cities'), parents_tags: [ltree('Top.Building.EmpireState'), ltree('Top.Building.EmpireState.381')]) + create_person.(name: 'John Bros', ltree_tags: ltree('Bottom.Cities.Melbourne'), parents_tags: [ltree('Right.Cars.Ford'), ltree('Right.Cars.Nissan')]) + create_person.(name: 'John Wick', ltree_tags: ltree('Bottom.Countries.Australia')) create_person.(name: 'Jade Doe', ltree_tags: ltree('Bottom.Countries.Australia.Brasil')) end @@ -235,103 +281,123 @@ def ltree(label_path) end it 'matches regular expression' do - expect(people.select(:name).where { ltree_tags.match('Bottom.Cities') }.one). - to eql(name: 'John Fake') + expect( + people.select(:name).where { ltree_tags.match('Bottom.Cities') }.one + ).to eql(name: 'John Fake') end it 'matches any lquery' do - expect(people.select(:name).where { ltree_tags.match_any(['Bottom', 'Bottom.Cities.*']) }.to_a). - to eql([{:name=>"John Wilkson"}, {:name=>"John Fake"}, {:name=>"John Bros"}]) + expect( + people.select(:name).where { ltree_tags.match_any(['Bottom', 'Bottom.Cities.*']) }.to_a + ).to eql([{ name: 'John Wilkson' }, { name: 'John Fake' }, { name: 'John Bros' }]) end it 'matches any lquery using string' do - expect(people.select(:name).where { ltree_tags.match_any('Bottom,Bottom.Cities.*') }.to_a). - to eql([{:name=>"John Wilkson"}, {:name=>"John Fake"}, {:name=>"John Bros"}]) + expect( + people.select(:name).where { ltree_tags.match_any('Bottom,Bottom.Cities.*') }.to_a + ).to eql([{ name: 'John Wilkson' }, { name: 'John Fake' }, { name: 'John Bros' }]) end it 'match ltextquery' do - expect(people.select(:name).where { ltree_tags.match_ltextquery('Countries & Brasil') }.one). - to eql(:name=>"Jade Doe") + expect( + people.select(:name).where { ltree_tags.match_ltextquery('Countries & Brasil') }.one + ).to eql(name: 'Jade Doe') end describe 'concatenation' do it 'concatenates ltrees' do - expect(people.select { (ltree_tags + ROM::Types::Values::TreePath.new('Moscu')).as(:ltree_tags) }.where { name.is('Jade Doe') }.one). - to eq(ltree_tags: ROM::Types::Values::TreePath.new('Bottom.Countries.Australia.Brasil.Moscu')) + expect( + people.select { (ltree_tags + ROM::Types::Values::TreePath.new('Moscu')).as(:ltree_tags) }.where { name.is('Jade Doe') }.one + ).to eq(ltree_tags: ROM::Types::Values::TreePath.new('Bottom.Countries.Australia.Brasil.Moscu')) end it 'concatenates strings' do - expect(people.select { (ltree_tags + 'Moscu').as(:ltree_tags) }.where { name.is('Jade Doe') }.one). - to eq(ltree_tags: ROM::Types::Values::TreePath.new('Bottom.Countries.Australia.Brasil.Moscu')) + expect( + people.select { + (ltree_tags + 'Moscu').as(:ltree_tags) # rubocop:disable Style/StringConcatenation + }.where { name.is('Jade Doe') }.one + ).to eq(ltree_tags: ROM::Types::Values::TreePath.new('Bottom.Countries.Australia.Brasil.Moscu')) end end it 'allow query by descendant of ltree' do - expect(people.select(:name).where { ltree_tags.descendant('Bottom.Countries') }.to_a). - to eql([{:name=>"John Wayne"}, {:name=>"John Wick"}, {:name=>"Jade Doe"}]) + expect( + people.select(:name).where { ltree_tags.descendant('Bottom.Countries') }.to_a + ).to eql([{ name: 'John Wayne' }, { name: 'John Wick' }, { name: 'Jade Doe' }]) end it 'allow query by any descendant contain in the array' do - expect(people.select(:name).where { ltree_tags.contain_descendant(['Bottom.Cities']) }.to_a). - to eql([{:name=>"John Fake"}, {:name=>"John Bros"}]) + expect( + people.select(:name).where { ltree_tags.contain_descendant(%w[Bottom.Cities]) }.to_a + ).to eql([{ name: 'John Fake' }, { name: 'John Bros' }]) end it 'allow query by ascendant of ltree' do - expect(people.select(:name).where { ltree_tags.ascendant('Bottom.Countries.Australia.Brasil') }.to_a). - to eql([{:name=>"John Wilkson"}, {:name=>"John Wayne"}, {:name=>"John Wick"}, {:name=>"Jade Doe"}]) + expect( + people.select(:name).where { ltree_tags.ascendant('Bottom.Countries.Australia.Brasil') }.to_a + ).to eql([{ name: 'John Wilkson' }, { name: 'John Wayne' }, { name: 'John Wick' }, { name: 'Jade Doe' }]) end it 'allow query by any ascendant contain in the array' do - expect(people.select(:name).where { ltree_tags.contain_ascendant(['Bottom.Cities']) }.to_a). - to eql([{:name=>"John Wilkson"}, {:name=>"John Fake"}]) + expect( + people.select(:name).where { ltree_tags.contain_ascendant(%w[Bottom.Cities]) }.to_a + ).to eql([{ name: 'John Wilkson' }, { name: 'John Fake' }]) end describe 'Using with in array ltree[]' do it 'contains any ltextquery' do - expect(people.select(:name).where { parents_tags.contain_any_ltextquery('Parks')}.to_a). - to eql([{:name=>"John Wayne"}]) + expect( + people.select(:name).where { parents_tags.contain_any_ltextquery('Parks') }.to_a + ).to eql([{ name: 'John Wayne' }]) end it 'contains any ancestor' do - expect(people.select(:name).where { parents_tags.contain_ancestor('Top.Building.EmpireState.381')}.to_a). - to eql([{:name=>"John Wilkson"}, {:name=>"John Fake"}]) + expect( + people.select(:name).where { parents_tags.contain_ancestor('Top.Building.EmpireState.381') }.to_a + ).to eql([{ name: 'John Wilkson' }, { name: 'John Fake' }]) end it 'contains any descendant' do - expect(people.select(:name).where { parents_tags.contain_descendant('Left')}.to_a). - to eql([{:name=>"John Wayne"}]) + expect( + people.select(:name).where { parents_tags.contain_descendant('Left') }.to_a + ).to eql([{ name: 'John Wayne' }]) end it 'allow to filter by matching lquery' do - expect(people.select(:name).where { parents_tags.match('T*|Left.*')}.to_a). - to eql([{:name=>"John Wilkson"}, {:name=>"John Wayne"}, {:name=>"John Fake"}]) + expect( + people.select(:name).where { parents_tags.match('T*|Left.*') }.to_a + ).to eql([{ name: 'John Wilkson' }, { name: 'John Wayne' }, { name: 'John Fake' }]) end it 'allow to filter by matching any lquery conatin in the array' do - expect(people.select(:name).where { parents_tags.match_any(['Top.*', 'Left.*'])}.to_a). - to eql([{:name=>"John Wilkson"}, {:name=>"John Wayne"}, {:name=>"John Fake"}]) + expect( + people.select(:name).where { parents_tags.match_any(%w[Top.* Left.*]) }.to_a + ).to eql([{ name: 'John Wilkson' }, { name: 'John Wayne' }, { name: 'John Fake' }]) end it 'finds first array entry that is an ancestor of ltree' do - expect(people.select(:name).where { parents_tags.find_ancestor('Left.Parks').not(nil)}.to_a). - to eql([{:name=>"John Wayne"}]) + expect( + people.select(:name).where { parents_tags.find_ancestor('Left.Parks').not(nil) }.to_a + ).to eql([{ name: 'John Wayne' }]) end it 'finds first array entry that is an descendant of ltree' do - expect(people.select(:name).where { parents_tags.find_descendant('Right.Cars').not(nil)}.to_a). - to eql([name: "John Bros"]) + expect( + people.select(:name).where { parents_tags.find_descendant('Right.Cars').not(nil) }.to_a + ).to eql([{ name: 'John Bros' }]) end it 'finds first array entry that is a match (lquery)' do - expect(people.select(:name).where { parents_tags.match_any_lquery('Right.*').not(nil)}.to_a). - to eql([{:name=>"John Bros"}]) + expect( + people.select(:name).where { parents_tags.match_any_lquery('Right.*').not(nil) }.to_a + ).to eql([{ name: 'John Bros' }]) end it 'finds first array entry that is a match (ltextquery)' do - expect(people.select(:name).where { parents_tags.match_any_ltextquery('EmpireState').not(nil)}.to_a). - to eql([{:name=>"John Fake"}]) + expect( + people.select(:name).where { parents_tags.match_any_ltextquery('EmpireState').not(nil) }.to_a + ).to eql([{ name: 'John Fake' }]) end end - end end diff --git a/spec/extensions/postgres/integration_spec.rb b/spec/extensions/postgres/integration_spec.rb index f806630b3..3e5fa2594 100644 --- a/spec/extensions/postgres/integration_spec.rb +++ b/spec/extensions/postgres/integration_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + RSpec.describe 'PostgreSQL extension', :postgres do include_context 'database setup' @@ -11,8 +13,8 @@ conn.create_table :pg_people do primary_key :id String :name - column :tags, "text[]" - column :allowed_subnets, "cidr[]" + column :tags, 'text[]' + column :allowed_subnets, 'cidr[]' end conf.relation(:people) do diff --git a/spec/extensions/postgres/type_serializer_spec.rb b/spec/extensions/postgres/type_serializer_spec.rb index 8f64cf47b..f3a8553ea 100644 --- a/spec/extensions/postgres/type_serializer_spec.rb +++ b/spec/extensions/postgres/type_serializer_spec.rb @@ -1,12 +1,14 @@ +# frozen_string_literal: true + RSpec.describe ROM::SQL::TypeSerializer[:postgres] do subject(:serializer) { ROM::SQL::TypeSerializer[:postgres] } it 'serializes PG types' do types = { - 'uuid' => ROM::SQL::Postgres::Types::UUID, + 'uuid' => ROM::SQL::Postgres::Types::UUID, 'money' => ROM::SQL::Postgres::Types::Money, 'bytea' => ROM::SQL::Postgres::Types::Bytea, - 'json' => ROM::SQL::Postgres::Types::JSON, + 'json' => ROM::SQL::Postgres::Types::JSON, 'jsonb' => ROM::SQL::Postgres::Types::JSONB, 'hstore' => ROM::SQL::Postgres::Types::HStore, 'inet' => ROM::SQL::Postgres::Types::IPAddress, diff --git a/spec/extensions/postgres/types_meta_spec.rb b/spec/extensions/postgres/types_meta_spec.rb index 1a13adf63..9a85bbccd 100644 --- a/spec/extensions/postgres/types_meta_spec.rb +++ b/spec/extensions/postgres/types_meta_spec.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + RSpec.describe 'ROM::SQL::Postgres::Types' do it 'has the correct meta db_type' do { 'uuid' => ROM::SQL::Postgres::Types::UUID, 'hstore' => ROM::SQL::Postgres::Types::HStore, - 'bytea' => ROM::SQL::Postgres::Types::Bytea, + 'bytea' => ROM::SQL::Postgres::Types::Bytea, 'money' => ROM::SQL::Postgres::Types::Money, 'xml' => ROM::SQL::Postgres::Types::XML, 'inet' => ROM::SQL::Postgres::Types::IPAddress, @@ -11,12 +13,12 @@ 'json' => ROM::SQL::Postgres::Types::JSON, 'jsonb' => ROM::SQL::Postgres::Types::JSONB, 'point' => ROM::SQL::Postgres::Types::Point, - 'line' => ROM::SQL::Postgres::Types::Line, + 'line' => ROM::SQL::Postgres::Types::Line, 'circle' => ROM::SQL::Postgres::Types::Circle, - 'box' => ROM::SQL::Postgres::Types::Box, - 'lseg' => ROM::SQL::Postgres::Types::LineSegment, + 'box' => ROM::SQL::Postgres::Types::Box, + 'lseg' => ROM::SQL::Postgres::Types::LineSegment, 'polygon' => ROM::SQL::Postgres::Types::Polygon, - 'path' => ROM::SQL::Postgres::Types::Path, + 'path' => ROM::SQL::Postgres::Types::Path, 'integer[]' => ROM::SQL::Postgres::Types.Array('integer') }.each do |meta_type, type| expect(type.meta[:db_type]).to eq meta_type diff --git a/spec/extensions/postgres/types_spec.rb b/spec/extensions/postgres/types_spec.rb index 8e2dbb751..0c5630360 100644 --- a/spec/extensions/postgres/types_spec.rb +++ b/spec/extensions/postgres/types_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'securerandom' RSpec.describe 'ROM::SQL::Postgres::Types' do @@ -170,7 +172,7 @@ end describe ROM::SQL::Types::PG::HStore do - let(:mapping) { Hash['hot' => 'cold'] } + let(:mapping) { { 'hot' => 'cold' } } let(:read_type) { described_class.meta[:read] } it 'covertss data to Sequel::Postgres::HStore' do @@ -241,7 +243,7 @@ describe ROM::SQL::Types::PG::Polygon do let(:first) { values::Point.new(8.5, 30.5) } - let(:second) {values::Point.new(7.5, 20.5) } + let(:second) { values::Point.new(7.5, 20.5) } let(:third) { values::Point.new(6.5, 10.5) } let(:polygon) { [first, second, third] } @@ -292,7 +294,7 @@ it 'read an empty value' do expect(described_class.meta[:read]['empty']).to eql( - values::Range.new(nil, nil, :'[]') + values::Range.new(nil, nil, :[]) ) end diff --git a/spec/extensions/sqlite/types_spec.rb b/spec/extensions/sqlite/types_spec.rb index 6643e5d19..fa7d416da 100644 --- a/spec/extensions/sqlite/types_spec.rb +++ b/spec/extensions/sqlite/types_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + RSpec.describe 'ROM::SQL::Types' do describe 'ROM::SQL::Types::SQLite::Object' do let(:type) { ROM::SQL::Types::SQLite::Object } diff --git a/spec/fixtures/migrations/20150403090603_create_carrots.rb b/spec/fixtures/migrations/20150403090603_create_carrots.rb index f391e921d..fb413698e 100644 --- a/spec/fixtures/migrations/20150403090603_create_carrots.rb +++ b/spec/fixtures/migrations/20150403090603_create_carrots.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + ROM::SQL.migration do change do create_table :carrots do diff --git a/spec/integration/commands/create_spec.rb b/spec/integration/commands/create_spec.rb index 75dfdb1bc..94da19757 100644 --- a/spec/integration/commands/create_spec.rb +++ b/spec/integration/commands/create_spec.rb @@ -96,6 +96,7 @@ def self.[](input) create_user.call(name: nil) } rescue ROM::SQL::Error + # ignore end }.to_not(change { container.relations.users.count }) end diff --git a/spec/integration/schema/inferrer/postgres_spec.rb b/spec/integration/schema/inferrer/postgres_spec.rb index c707788a1..8a6fbe14a 100644 --- a/spec/integration/schema/inferrer/postgres_spec.rb +++ b/spec/integration/schema/inferrer/postgres_spec.rb @@ -177,22 +177,22 @@ let(:values) { ROM::SQL::Postgres::Values } let(:point) { ROM::SQL::Postgres::Values::Point.new(7.5, 30.5) } - let(:point_2) { ROM::SQL::Postgres::Values::Point.new(8.5, 35.5) } + let(:point2) { ROM::SQL::Postgres::Values::Point.new(8.5, 35.5) } let(:line) { ROM::SQL::Postgres::Values::Line.new(2.3, 4.9, 3.1415) } let(:dns) { IPAddr.new('8.8.8.8') } let(:mapping) { { 'hot' => 'cold' } } let(:circle) { ROM::SQL::Postgres::Values::Circle.new(point, 1.0) } - let(:lseg) { ROM::SQL::Postgres::Values::LineSegment.new(point, point_2) } - let(:box_corrected) { ROM::SQL::Postgres::Values::Box.new(point_2, point) } + let(:lseg) { ROM::SQL::Postgres::Values::LineSegment.new(point, point2) } + let(:box_corrected) { ROM::SQL::Postgres::Values::Box.new(point2, point) } let(:box) do - upper_left = ROM::SQL::Postgres::Values::Point.new(point.x, point_2.y) - lower_right = ROM::SQL::Postgres::Values::Point.new(point_2.x, point.y) + upper_left = ROM::SQL::Postgres::Values::Point.new(point.x, point2.y) + lower_right = ROM::SQL::Postgres::Values::Point.new(point2.x, point.y) ROM::SQL::Postgres::Values::Box.new(upper_left, lower_right) end - let(:polygon) { [point, point_2] } - let(:closed_path) { ROM::SQL::Postgres::Values::Path.new([point, point_2], :closed) } - let(:open_path) { ROM::SQL::Postgres::Values::Path.new([point, point_2], :open) } + let(:polygon) { [point, point2] } + let(:closed_path) { ROM::SQL::Postgres::Values::Path.new([point, point2], :closed) } + let(:open_path) { ROM::SQL::Postgres::Values::Path.new([point, point2], :open) } let(:ltree) { ROM::Types::Values::TreePath.new('Top.Countries.Europe.Russia') } let(:int4range) { values::Range.new(0, 2, :'[)') }