Skip to content

Instantly share code, notes, and snippets.

@manveru
Last active December 2, 2019 23:31
Show Gist options
  • Save manveru/1d13a2353fca598116f83d2438d08a6f to your computer and use it in GitHub Desktop.
Save manveru/1d13a2353fca598116f83d2438d08a6f to your computer and use it in GitHub Desktop.
Additional types for Avram
record Bytea, bytes : Bytes
struct Bytea
def self.adapter
Lucky
end
def blank?
@bytes.size == 0
end
module Lucky
alias ColumnType = Bytes
include Avram::Type
def parse(value : String) : SuccessfulCast(Bytea) | FailedCast
FailedCast.new
end
def parse(value : Bytes) : SuccessfulCast(Bytea)
SuccessfulCast(Bytea).new(Bytea.new(value))
end
def to_db(value : Bytea) : String
"\\x" + value.bytes.hexstring
end
end
end
module Avram::Migrator::Columns
class ByteaColumn(T) < Base
@default : T | Nil = nil
def initialize(@name, @nilable, @default)
end
def column_type : String
"bytea"
end
def self.prepare_value_for_database(value : Bytea)
escape_literal value.bytes
end
end
end
alias Point = PG::Geo::Point
struct Point
def self.adapter
Lucky
end
def latitude
@y
end
def longitude
@x
end
def to_s
"(#{@x},#{@y})"
end
module Lucky
alias ColumnType = Point
include Avram::Type
def from_db!(value : Point)
value
end
def parse(value : String) : SuccessfulCast(Point) | FailedCast
if md = value.match(/\((\d+(?:\.\d+)?),(\d+(?:\.\d+)?)\)/)
SuccessfulCast(Point).new(Point.new(md[1].to_f64, md[2].to_f64))
else
FailedCast.new
end
end
def parse(value : Point)
SuccessfulCast(Point).new(value)
end
def to_db(value : Point)
"(#{value.x},#{value.y})"
end
end
end
module Avram::Migrator::Columns
class PointColumn(T) < Base
@default : T | Nil = nil
def initialize(@name, @nilable, @default)
end
def column_type : String
"point"
end
def self.prepare_value_for_database(value : Point)
escape_literal "(#{value.x},#{value.y})"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment