Class: ActiveRecord::ConnectionAdapters::PostgreSQLColumn

Inherits:
Column
  • Object
show all
Defined in:
lib/rubyrep/connection_extenders/postgresql_extender.rb

Overview

PostgreSQL-specific extensions to column definitions in a table.

Class Method Summary collapse

Methods inherited from Column

fast_string_to_time

Class Method Details

.binary_to_string(value) ⇒ Object

Unescapes bytea output from a database to the binary string it represents.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/rubyrep/connection_extenders/postgresql_extender.rb', line 35

def self.binary_to_string(value)
  # In each case, check if the value actually is escaped PostgreSQL bytea output
  # or an unescaped Active Record attribute that was just written.
  if PGconn.respond_to?(:unescape_bytea)
    self.class.module_eval do
      define_method(:binary_to_string) do |value|
        if value =~ /\\\d{3}/
          PGconn.unescape_bytea(value)
        else
          value
        end
      end
    end
  else
    self.class.module_eval do
      define_method(:binary_to_string) do |value|
        if value =~ /\\\d{3}/
          result = ''
          i, max = 0, value.size
          while i < max
            char = value[i]
            if char == ?\\
              if value[i+1] == ?\\
                char = ?\\
                i += 1
              else
                char = value[i+1..i+3].oct
                i += 3
              end
            end
            result << char
            i += 1
          end
          result
        else
          value
        end
      end
    end
  end
  self.class.binary_to_string(value)
end

.string_to_binary(value) ⇒ Object

Escapes binary strings for bytea input to the database.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/rubyrep/connection_extenders/postgresql_extender.rb', line 13

def self.string_to_binary(value)
  if PGconn.respond_to?(:escape_bytea)
    self.class.module_eval do
      define_method(:string_to_binary) do |value|
        PGconn.escape_bytea(value) if value
      end
    end
  else
    self.class.module_eval do
      define_method(:string_to_binary) do |value|
        if value
          result = ''
          value.each_byte { |c| result << sprintf('\\\\%03o', c) }
          result
        end
      end
    end
  end
  self.class.string_to_binary(value)
end