Skip to content

Commit 4b87df3

Browse files
committed
Auto validate underlying enum value in pg_auto_validate_enums
Otherwise, if the column method is overridden to return an invalid enum value, there can be a false positive when saving.
1 parent 0c5b992 commit 4b87df3

File tree

2 files changed

+12
-5
lines changed

2 files changed

+12
-5
lines changed

lib/sequel/plugins/pg_auto_validate_enums.rb

+4-3
Original file line numberDiff line numberDiff line change
@@ -29,16 +29,17 @@ def self.apply(model, opts=OPTS)
2929

3030
# Load the pg_enum extension into the database, and reload the schema
3131
# if it is already loaded. The opts given are used for the validates_includes
32-
# validations (with allow_nil: true enabled by default, to avoid issues with
33-
# nullable enum columns).
32+
# validations (with allow_nil: true and from: :values enabled by default,
33+
# to avoid issues with nullable enum columns and cases where the column
34+
# method has been overridden.
3435
def self.configure(model, opts=OPTS)
3536
model.instance_exec do
3637
db.extension(:pg_enum) unless @db.instance_variable_get(:@enum_labels)
3738
if @db_schema
3839
get_db_schema(true)
3940
_get_pg_pg_auto_validate_enums_metadata
4041
end
41-
@pg_auto_validate_enums_opts = {allow_nil: true}.merge!(opts).freeze
42+
@pg_auto_validate_enums_opts = {allow_nil: true, from: :values}.merge!(opts).freeze
4243
end
4344
end
4445

spec/extensions/pg_auto_validate_enums_spec.rb

+8-2
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,12 @@ def @db.schema(table, *)
2424
@o.errors.must_equal({:c => ['is not in range or set: ["a", "b", "test"]']})
2525
end
2626

27+
it "validates underlying enum value, not method return value" do
28+
@o.c = "a"
29+
def @o.c; "invalid" end
30+
@o.valid?.must_equal true
31+
end
32+
2733
it "treats plugin options as validates_includes options for validations" do
2834
@c.plugin :pg_auto_validate_enums, :message=>"is not valid"
2935
@o.c = "c"
@@ -61,8 +67,8 @@ def @db.schema(table, *)
6167
end
6268

6369
it "exposes options in .pg_auto_validate_enums_opts" do
64-
@c.pg_auto_validate_enums_opts.must_equal(:allow_nil => true)
70+
@c.pg_auto_validate_enums_opts.must_equal(:allow_nil => true, :from => :values)
6571
@c.plugin :pg_auto_validate_enums, :message=>"is not valid"
66-
@c.pg_auto_validate_enums_opts.must_equal(:allow_nil => true, :message => "is not valid")
72+
@c.pg_auto_validate_enums_opts.must_equal(:allow_nil => true, :message => "is not valid", :from => :values)
6773
end
6874
end

0 commit comments

Comments
 (0)