diff --git a/CHANGELOG.md b/CHANGELOG.md index 6cd2a04c..2728bbe5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Added +- Added `PG::Range` columns for integer, numeric, and timestamp values, preserving empty values, unbounded ends, and inclusive/exclusive bounds. Native Crystal ranges and PostgreSQL range strings are accepted as input. - Added expression `after?` and `before?` predicates for readable greater-than and less-than comparisons between SQL expressions or literal values. - `JSON::Any` model columns now accept JSON-serializable Crystal collections such as hashes, arrays, and named tuples. - Added `Model#modified?` for checking whether a new or changed model requires database persistence. diff --git a/README.md b/README.md index f3f020c1..1d744b09 100644 --- a/README.md +++ b/README.md @@ -158,6 +158,19 @@ For ordered through associations with raw SQL projections, `to_sql` may require a live database connection to resolve output column names. Lustra uses PostgreSQL's describe protocol without executing the query. +## PostgreSQL Ranges + +Declare range columns using `PG::Range(T)`, for example +`column availability : PG::Range(Time)?` in a model backed by a `tsrange` or +`tstzrange` column. Supported bound types are `Int32`, `Int64`, `PG::Numeric`, +`BigDecimal`, and `Time`. + +Assignments accept native Crystal ranges and PostgreSQL range strings. Returned +values preserve both bound inclusivity flags, unbounded ends, and empty ranges. +SQL `NULL` is represented by `nil`; an empty range is a non-nil value with +`empty? == true`. Keep `PG::Range` for empty ranges or exclusive lower bounds; +use `to_crystal_range` only for nonempty values that Crystal can represent. + ## Documentation - Manual: https://crystal-garage.gitbook.io/lustra-docs/ diff --git a/shard.yml b/shard.yml index 7e13c0e9..95e1a197 100644 --- a/shard.yml +++ b/shard.yml @@ -18,7 +18,7 @@ dependencies: branch: master pg: github: will/crystal-pg - version: "~> 0.29.0" + branch: master inflector: github: phoffer/inflector.cr version: ">= 0.1.8" diff --git a/spec/data/example_models.cr b/spec/data/example_models.cr index d8d874fa..37623f2b 100644 --- a/spec/data/example_models.cr +++ b/spec/data/example_models.cr @@ -285,6 +285,21 @@ class FloatData column temperature : Float32? end +class RangeData + include Lustra::Model + + primary_key + + column name : String? + column int32_range : PG::Range(Int32)? + column int64_range : PG::Range(Int64)? + column numeric_range : PG::Range(BigDecimal)? + column pg_numeric_range : PG::Range(PG::Numeric)? + column time_range : PG::Range(Time)? + + self.table = "range_data" +end + class ModelWithinAnotherSchema include Lustra::Model @@ -518,6 +533,17 @@ class ModelSpecMigration123 t.timestamps end + create_table :range_data do |t| + t.column "name", "string", null: true + t.column "int32_range", "int4range", null: true + t.column "int64_range", "int8range", null: true + t.column "numeric_range", "numrange", null: true + t.column "pg_numeric_range", "numrange", null: true + t.column "time_range", "tsrange", null: true + + t.timestamps + end + # Geometric test tables create_table :locations do |t| t.column "name", "string", null: false diff --git a/spec/model/converters/range_converter_spec.cr b/spec/model/converters/range_converter_spec.cr new file mode 100644 index 00000000..1ab13616 --- /dev/null +++ b/spec/model/converters/range_converter_spec.cr @@ -0,0 +1,100 @@ +require "../../spec_helper" + +module RangeConverterSpec + describe "Lustra::Model::Converter Range Converters" do + describe "RangeConverter(Int32)" do + it "parses and serializes int ranges" do + converter = Lustra::Model::Converter::RangeConverter(Int32) + + # parse textual range + r = converter.to_column("[1,10)") + r.should eq(1...10) + + # serialize Range -> PG textual + serialized = converter.to_db(converter.to_column(Range.new(1_i32, 10_i32, true))) + serialized.should eq("[1,10)") + + # empty remains distinct from SQL NULL + converter.to_column("empty").not_nil!.empty?.should be_true + + # unbounded lower bound + r2 = converter.to_column("(,10]") + r2.should eq(..10) + end + end + + describe "RangeConverter(Int64)" do + it "parses and serializes big int ranges" do + converter = Lustra::Model::Converter::RangeConverter(Int64) + + r = converter.to_column("[10000000000,20000000000)") + r.should eq(10000000000...20000000000) + + serialized = converter.to_db(converter.to_column(Range.new(10000000000, 20000000000, true))) + serialized.should eq("[10000000000,20000000000)") + + # endless upper bound + r2 = converter.to_column("[1,)") + r2.should eq(1...) + end + end + + it "preserves bound flags when converting PostgreSQL range values" do + converter = Lustra::Model::Converter::RangeConverter(BigDecimal) + {true, false}.each do |lower_inclusive| + {true, false}.each do |upper_inclusive| + value = PG::Range(Int32).new(1, 10, + lower_inclusive: lower_inclusive, upper_inclusive: upper_inclusive) + converted = converter.to_column(value).not_nil! + converted.begin.should eq(BigDecimal.new(1)) + converted.end.should eq(BigDecimal.new(10)) + converted.lower_inclusive.should eq(lower_inclusive) + converted.upper_inclusive.should eq(upper_inclusive) + end + end + end + + it "parses numeric strings without losing decimal precision" do + converter = Lustra::Model::Converter::RangeConverter(PG::Numeric) + {"0", "-0.00001", "12345678901234567890.123456789", "1e-20", "1.2300"}.each do |text| + value = converter.to_column("[#{text},#{text}]").not_nil! + BigDecimal.new(value.begin.to_s).should eq(BigDecimal.new(text)) + BigDecimal.new(value.end.to_s).should eq(BigDecimal.new(text)) + end + end + + it "rejects malformed and empty textual input instead of treating it as SQL NULL" do + converter = Lustra::Model::Converter::RangeConverter(Int32) + {"", "[1,2", "[1,2,3]", %(["1,2]), %(["",2]), %(["1""2",3])}.each do |text| + expect_raises(ArgumentError) { converter.to_column(text) } + end + end + + describe "RangeConverter(Time)" do + it "parses PostgreSQL ISO timestamps and preserves time zone offsets" do + converter = Lustra::Model::Converter::RangeConverter(Time) + value = converter.to_column(%(["2024-01-01 10:30:00.123456+02","2024-01-01 12:30:00+02"])).not_nil! + value.begin.should eq(Time.utc(2024, 1, 1, 8, 30, 0, nanosecond: 123_456_000)) + value.end.should eq(Time.utc(2024, 1, 1, 10, 30)) + converter.to_db(value).should eq("[2024-01-01T08:30:00.123456000Z,2024-01-01T10:30:00.000000000Z]") + end + + it "parses and serializes time ranges" do + converter = Lustra::Model::Converter::RangeConverter(Time) + + txt = "[2020-01-01T00:00:00Z,2020-12-31T23:59:59Z]" + r = converter.to_column(txt) + start_t = Time.utc(2020, 1, 1) + end_t = Time.utc(2020, 12, 31, 23, 59, 59) + r.should eq(start_t..end_t) + + serialized = converter.to_db(converter.to_column(Range.new(start_t, end_t, false))) + serialized.should eq("[2020-01-01T00:00:00.000000000Z,2020-12-31T23:59:59.000000000Z]") + + # unbounded both sides (both bounds empty) + r2 = converter.to_column("(,)") + r2.should eq(...) + end + end + end +end diff --git a/spec/model/range_spec.cr b/spec/model/range_spec.cr new file mode 100644 index 00000000..15f16f67 --- /dev/null +++ b/spec/model/range_spec.cr @@ -0,0 +1,155 @@ +require "../spec_helper" +require "../data/example_models" + +module RangeSpec + describe "PostgreSQL Range Types Test Suite" do + it "creates and retrieves records with range" do + temporary do + reinit_example_models + + range_record = RangeData.create!( + name: "Test Range Record", + int32_range: 1..10, + int64_range: 1000..2000, + numeric_range: BigDecimal.new("1.5")..BigDecimal.new("2.5"), + time_range: Time.utc(2024, 1, 1)..Time.utc(2024, 12, 31) + ) + + range_record.int32_range.should eq(1...11) + range_record.int64_range.should eq(1000...2001) + range_record.numeric_range.should eq(BigDecimal.new("1.5")..BigDecimal.new("2.5")) + range_record.time_range.should eq(Time.utc(2024, 1, 1)..Time.utc(2024, 12, 31)) + end + end + + it "creates and retrieves records with endless/beginless range" do + temporary do + reinit_example_models + + range_record = RangeData.create!( + name: "Test Range Record", + int32_range: ..10, + int64_range: 1000.., + numeric_range: ..BigDecimal.new("2.5"), + time_range: Time.utc(2024, 1, 1).. + ) + + range_record.int32_range.should eq(...11) + range_record.int64_range.should eq(1000...) + range_record.numeric_range.should eq(..BigDecimal.new("2.5")) + range_record.time_range.should eq(Time.utc(2024, 1, 1)...) + end + end + + it "preserves empty, unbounded, and null range values separately" do + temporary do + reinit_example_models + {nil, "empty", "(,)"}.each do |input| + record = RangeData.create!(int32_range: input, int64_range: input, + numeric_range: input, pg_numeric_range: input, time_range: input) + record.reload + {record.int32_range, record.int64_range, record.numeric_range, record.pg_numeric_range, record.time_range}.each do |value| + if input.nil? + value.should be_nil + else + value = value.not_nil! + value.empty?.should eq(input == "empty") + value.begin.should be_nil + value.end.should be_nil + value.lower_inclusive.should be_false + value.upper_inclusive.should be_false + end + end + end + end + end + + it "preserves exclusive lower bounds in strings and decoded values" do + temporary do + reinit_example_models + record = RangeData.create!( + int32_range: "(1,10]", + int64_range: "(100,200)", + numeric_range: "(1.5,2.5]", + pg_numeric_range: "(1.5,2.5]", + time_range: "(\"2024-01-01 00:00:00\",\"2024-02-01 00:00:00\"]" + ) + record.reload + record.int32_range.should eq(2...11) + record.int64_range.should eq(101_i64...200_i64) + {record.numeric_range, record.pg_numeric_range, record.time_range}.each do |value| + value = value.not_nil! + value.lower_inclusive.should be_false + value.upper_inclusive.should be_true + end + record.numeric_range.not_nil!.begin.should eq(BigDecimal.new("1.5")) + record.pg_numeric_range.not_nil!.begin.to_s.should eq("1.5") + record.time_range.not_nil!.begin.should eq(Time.utc(2024, 1, 1)) + end + end + + it "keeps fully unbounded native range input nonempty" do + temporary do + reinit_example_models + record = RangeData.create!(int32_range: Range(Int32?, Int32?).new(nil, nil, true)) + record.int32_range.not_nil!.empty?.should be_false + Lustra::SQL.select("isempty(int32_range)").from(:range_data) + .where(id: record.id).scalar(Bool).should be_false + end + end + + it "filters range columns with native and model range values" do + temporary do + reinit_example_models + record = RangeData.create!(int32_range: 1..10, + numeric_range: "(1.5,2.5]", time_range: Time.utc(2024, 1, 1)..Time.utc(2024, 2, 1)) + RangeData.query.where { int32_range == record.int32_range }.count.should eq(1_i64) + RangeData.query.where { int32_range == (1..10) }.count.should eq(1_i64) + RangeData.query.where { numeric_range == record.numeric_range }.count.should eq(1_i64) + RangeData.query.where { time_range == record.time_range }.count.should eq(1_i64) + RangeData.create!(int32_range: "empty") + RangeData.query.where { int32_range == PG::Range(Int32).empty }.count.should eq(1_i64) + end + end + + it "inserts PostgreSQL ranges through low-level queries" do + temporary do + reinit_example_models + Lustra::SQL.insert(:range_data, {int32_range: PG::Range(Int32).new(1, 10, upper_inclusive: true)}).execute + Lustra::SQL.insert(:range_data, {int32_range: PG::Range(Int32).empty}).execute + records = RangeData.query.order_by(:id).to_a + records[0].int32_range.should eq(1...11) + records[1].int32_range.not_nil!.empty?.should be_true + end + end + + it "preserves range metadata through direct column updates and JSON" do + temporary do + reinit_example_models + record = RangeData.create!(int32_range: 1..10) + value = PG::Range(BigDecimal).new(BigDecimal.new("1.5"), BigDecimal.new("2.5"), + lower_inclusive: false, upper_inclusive: true) + record.update_column(:numeric_range, value) + record.reload.numeric_range.should eq(value) + JSON.parse(record.to_json)["numeric_range"].as_s.should eq("(1.5,2.5]") + end + end + + it "creates and retrieves records with raw sql range" do + temporary do + reinit_example_models + + range_record = RangeData.create!( + name: "Test Range Record", + int32_range: "[,11)", + int64_range: "[1000,)", + numeric_range: "[1.5,2.5]", + ) + + range_record.int32_range.should eq(...11) + range_record.int64_range.should eq(1000...) + range_record.numeric_range.should eq(BigDecimal.new("1.5")..BigDecimal.new("2.5")) + end + end + end +end diff --git a/src/lustra/expression/expression.cr b/src/lustra/expression/expression.cr index d83fe7b6..7a09e11a 100644 --- a/src/lustra/expression/expression.cr +++ b/src/lustra/expression/expression.cr @@ -116,6 +116,11 @@ class Lustra::Expression {"'", x.gsub('\'', "''"), "'"}.join end + # :nodoc: + def self.safe_literal(x : ::Range | PG::Range) : String + safe_literal(SQL::RangeLiteral.format(x)) + end + # :nodoc: def self.safe_literal(x : ::Lustra::SQL::SelectBuilder) {"(", x.to_sql, ")"}.join diff --git a/src/lustra/expression/nodes/literal.cr b/src/lustra/expression/nodes/literal.cr index 921f42d5..4ab294cd 100644 --- a/src/lustra/expression/nodes/literal.cr +++ b/src/lustra/expression/nodes/literal.cr @@ -7,6 +7,8 @@ class Lustra::Expression::Node::Literal < Lustra::Expression::Node def initialize(value) if value.is_a?(AvailableLiteral) @value = value + elsif value.is_a?(::Range) || value.is_a?(PG::Range) + @value = SQL::RangeLiteral.format(value) elsif value.responds_to?(:to_sql) @value = value.to_sql else diff --git a/src/lustra/extensions/core_ext.cr b/src/lustra/extensions/core_ext.cr index f64f71d1..fbcc56bc 100644 --- a/src/lustra/extensions/core_ext.cr +++ b/src/lustra/extensions/core_ext.cr @@ -8,6 +8,18 @@ struct Char end end +struct Range + def to_json(json : JSON::Builder) + json.string(Lustra::SQL::RangeLiteral.format(self)) + end +end + +struct PG::Range + def to_json(json : JSON::Builder) + json.string(Lustra::SQL::RangeLiteral.format(self)) + end +end + class Crypto::Bcrypt::Password def to_json(json : JSON::Builder) : Nil json.string(self) diff --git a/src/lustra/model/converters/range_converter.cr b/src/lustra/model/converters/range_converter.cr new file mode 100644 index 00000000..38610445 --- /dev/null +++ b/src/lustra/model/converters/range_converter.cr @@ -0,0 +1,89 @@ +require "./base" +require "../../sql/range_literal" + +# Keep PostgreSQL's empty and bound flags; callers can explicitly convert a +# representable value with PG::Range#to_crystal_range when needed. +module Lustra::Model::Converter::RangeConverter(T) + def self.to_column(value) : PG::Range(T)? + case value + when Nil + nil + when PG::Range + return PG::Range(T).empty if value.empty? + PG::Range(T).new(bound(value.begin), bound(value.end), + lower_inclusive: value.lower_inclusive, upper_inclusive: value.upper_inclusive) + when ::Range + lower = bound(value.begin) + upper = bound(value.end) + return PG::Range(T).empty if !lower.nil? && lower == upper && value.excludes_end? + PG::Range(T).new(lower, upper, + lower_inclusive: !lower.nil?, upper_inclusive: !upper.nil? && !value.excludes_end?) + when String + SQL::RangeLiteral.parse(value, T) { |text| bound(text) } + else + raise ArgumentError.new("Cannot convert #{value.class} to PG::Range(#{T})") + end + end + + def self.to_db(value : PG::Range(T)?) : String? + value.try { |range| SQL::RangeLiteral.format(range) } + end + + private def self.bound(value) : T? + return if value.nil? + return value if value.is_a?(T) + {% if T == Int32 %} + value.to_s.to_i32 + {% elsif T == Int64 %} + value.to_s.to_i64 + {% elsif T == BigDecimal %} + BigDecimal.new(value.to_s) + {% elsif T == PG::Numeric %} + numeric(value.to_s) + {% elsif T == Time %} + text = value.to_s + return Time.parse_utc(text, "%F") if text.size == 10 + text = text.sub(' ', 'T') + if zone = text.index('+', 10) || text.index('-', 10) + text += ":00" if text.size - zone == 3 + elsif !text.ends_with?('Z') && !text.ends_with?('z') + text += 'Z' + end + Time.parse_iso8601(text) + {% else %} + {% raise "Unsupported range bound type: #{T}" %} + {% end %} + end + + # PG::Numeric exposes a binary-value constructor. Build its base-10000 digits + # from BigDecimal's exact coefficient and scale, without passing through Float. + private def self.numeric(text : String) : PG::Numeric + if text == "NaN" + return PG::Numeric.new(0_i16, 0_i16, PG::Numeric::Sign::Nan.value, 0_i16, [] of Int16) + end + decimal = BigDecimal.new(text) + scale = decimal.scale.to_i + padding = (4 - scale % 4) % 4 + coefficient = decimal.value.abs * BigInt.new(10) ** padding + digits = [] of Int16 + until coefficient.zero? + digits << (coefficient % 10_000).to_i16 + coefficient //= 10_000 + end + digits.reverse! + weight = digits.empty? ? 0 : digits.size - 1 - (scale + padding) // 4 + while digits.last? == 0 + digits.pop + end + sign = decimal.value < 0 ? PG::Numeric::Sign::Neg : PG::Numeric::Sign::Pos + PG::Numeric.new(digits.size.to_i16, weight.to_i16, sign.value, scale.to_i16, digits) + end +end + +module Lustra::Model::Converter + add_converter("PG::Range(Int32)", Lustra::Model::Converter::RangeConverter(Int32)) + add_converter("PG::Range(Int64)", Lustra::Model::Converter::RangeConverter(Int64)) + add_converter("PG::Range(Time)", Lustra::Model::Converter::RangeConverter(Time)) + add_converter("PG::Range(PG::Numeric)", Lustra::Model::Converter::RangeConverter(PG::Numeric)) + add_converter("PG::Range(BigDecimal)", Lustra::Model::Converter::RangeConverter(BigDecimal)) +end diff --git a/src/lustra/sql/range_literal.cr b/src/lustra/sql/range_literal.cr new file mode 100644 index 00000000..7bd80e37 --- /dev/null +++ b/src/lustra/sql/range_literal.cr @@ -0,0 +1,96 @@ +# :nodoc: +# PostgreSQL range text preserves empty values and both bound inclusivity flags. +module Lustra::SQL::RangeLiteral + extend self + + def format(value : PG::Range) : String + return "empty" if value.empty? + format_bounds(value, value.lower_inclusive, value.upper_inclusive) + end + + def format(value : ::Range) : String + if !value.begin.nil? && value.begin == value.end && value.excludes_end? + return "empty" + end + format_bounds(value, !value.begin.nil?, !value.end.nil? && !value.excludes_end?) + end + + private def format_bounds(value, lower_inclusive : Bool, upper_inclusive : Bool) : String + lower = value.begin.try { |bound| format_bound(bound) } || "" + upper = value.end.try { |bound| format_bound(bound) } || "" + "#{lower_inclusive ? '[' : '('}#{lower},#{upper}#{upper_inclusive ? ']' : ')'}" + end + + private def format_bound(value : Time) : String + value.to_utc.to_rfc3339(fraction_digits: 9) + end + + private def format_bound(value) : String + text = value.to_s + if text.empty? || text.each_char.any? { |char| char.whitespace? || {'"', '\\', ',', '(', ')', '[', ']'}.includes?(char) } + %("#{text.gsub('\\', "\\\\").gsub('"', "\\\"")}") + else + text + end + end + + def parse(text : String, type : T.class, & : String -> T?) : PG::Range(T) forall T + text = text.strip + return PG::Range(T).empty if text == "empty" + unless text.size >= 3 && {'[', '('}.includes?(text[0]) && {']', ')'}.includes?(text[-1]) + raise ArgumentError.new("Invalid PostgreSQL range: #{text}") + end + + bounds = split_bounds(text[1...-1]) + lower = bounds[0].try { |bound| yield bound } + upper = bounds[1].try { |bound| yield bound } + PG::Range(T).new(lower, upper, + lower_inclusive: !lower.nil? && text[0] == '[', + upper_inclusive: !upper.nil? && text[-1] == ']') + end + + # Range text uses double quotes and backslashes to escape bound delimiters. + private def split_bounds(text : String) : Array(String?) + bounds = [] of String? + buffer = IO::Memory.new + quoted = false + escaped = false + present = false + reader = Char::Reader.new(text) + while reader.has_next? + char = reader.current_char + if escaped + buffer << char + escaped = false + present = true + elsif char == '\\' + escaped = true + elsif char == '"' + if quoted && reader.peek_next_char == '"' + buffer << '"' + reader.next_char + else + quoted = !quoted + end + present = true + elsif char == ',' && !quoted + bounds << bound_text(buffer, present) + buffer.clear + present = false + else + buffer << char + present ||= !char.whitespace? + end + reader.next_char + end + if bounds.size != 1 || quoted || escaped + raise ArgumentError.new("Invalid PostgreSQL range bounds: #{text}") + end + bounds << bound_text(buffer, present) + end + + # Quoted empty strings are values; only omitted bounds are infinite. + private def bound_text(buffer : IO::Memory, present : Bool) : String? + buffer.to_s.strip if present + end +end diff --git a/src/lustra/sql/sql.cr b/src/lustra/sql/sql.cr index f3fcc85a..6c4a3138 100644 --- a/src/lustra/sql/sql.cr +++ b/src/lustra/sql/sql.cr @@ -70,11 +70,15 @@ module Lustra JSON::Any | JSON::PullParser | PG::Interval | ::Crypto::Bcrypt::Password | PG::Geo::Point | PG::Geo::Line | PG::Geo::LineSegment | PG::Geo::Box | PG::Geo::Circle | PG::Geo::Path | PG::Geo::Polygon | + PG::Range(Int32) | PG::Range(Int64) | PG::Range(PG::Numeric) | PG::Range(BigDecimal) | PG::Range(Time) | + Range(Int32?, Int32?) | Range(Int64?, Int64?) | Range(PG::Numeric?, PG::Numeric?) | Range(Time?, Time?) | Slice(UInt8) | Array(PG::BoolArray) | Array(PG::CharArray) | Array(PG::Int16Array) | Array(PG::Int32Array) | Array(PG::Int64Array) | Array(PG::Float32Array) | Array(PG::Float64Array) | Array(PG::NumericArray) | Array(PG::StringArray) | Array(PG::TimeArray) | Array(PG::UUIDArray) | + Array(PG::Range(Int32)) | Array(PG::Range(Int64)) | Array(PG::Range(PG::Numeric)) | Array(PG::Range(Time)) | + Array(Range(Int32?, Int32?)) | Array(Range(Int64?, Int64?)) | Array(Range(PG::Numeric?, PG::Numeric?)) | Array(Range(Time?, Time?)) | Lustra::Expression::UnsafeSql | Lustra::Expression::Literal? alias Symbolic = String | Symbol