Class: DBI::DBD::Pg::Type::ByteA

Inherits:
Object
  • Object
show all
Defined in:
lib/dbd/pg/type.rb

Overview

ByteA is a special escaped form of binary data, suitable for inclusion in queries.

This class is an attempt to abstract that type so you do not have to concern yourself with the conversion issues.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(obj) ⇒ ByteA

Build a new ByteA object.

The data supplied is the unescaped binary data you wish to put in the database.



24
25
26
27
28
29
# File 'lib/dbd/pg/type.rb', line 24

def initialize(obj)
    @original = obj
    @escaped = escape_bytea(obj)
    @original.freeze
    @escaped.freeze
end

Instance Attribute Details

#escapedObject (readonly)

Returns the value of attribute escaped.



16
17
18
# File 'lib/dbd/pg/type.rb', line 16

def escaped
  @escaped
end

#originalObject (readonly)

Returns the value of attribute original.



15
16
17
# File 'lib/dbd/pg/type.rb', line 15

def original
  @original
end

Class Method Details

.escape_bytea(str) ⇒ Object

Class method to escape the data into ByteA format.



48
49
50
# File 'lib/dbd/pg/type.rb', line 48

def self.escape_bytea(str)
    self.new(str).escaped
end

.parse(obj) ⇒ Object

Class method to unescape the ByteA data and present it as a string.



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/dbd/pg/type.rb', line 55

def self.parse(obj)

    return nil if obj.nil?

    # FIXME there's a bug in the upstream 'pg' driver that does not
    # properly decode bytea, leaving in an extra slash for each decoded
    # character.
    #
    # Fix this for now, but beware that we'll have to unfix this as
    # soon as they fix their end.
    ret = PG::Connection.unescape_bytea(obj)

    # XXX 
    # String#split does not properly create a full array if the the
    # string ENDS in the split regex, unless this oddball -1 argument is supplied.
    #
    # Another way of saying this:
    # if foo = "foo\\\\\" and foo.split(/\\\\/), the result will be
    # ["foo"]. You can add as many delimiters to the end of the string
    # as you'd like - the result is no different.
    #

    ret = ret.split(/\\\\/, -1).collect { |x| x.length > 0 ? x.gsub(/\\[0-7]{3}/) { |y| y[1..3].oct.chr } : "" }.join("\\")
    ret.gsub!(/''/, "'")
    return ret
end

Instance Method Details

#escape_bytea(str) ⇒ Object

Escapes the supplied data. Has no effect on the object.



34
35
36
# File 'lib/dbd/pg/type.rb', line 34

def escape_bytea(str)
    PG::Connection.escape_bytea(str)
end

#to_sObject

Returns the original data.



41
42
43
# File 'lib/dbd/pg/type.rb', line 41

def to_s
    return @original.dup
end