Class: MiniSql::Postgres::Connection

Inherits:
Connection show all
Defined in:
lib/mini_sql/postgres/connection.rb,
lib/mini_sql/postgres_jdbc/connection.rb

Defined Under Namespace

Classes: IPAddrCoder, NumericCoder

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Connection

#build, get, #to_sql

Constructor Details

#initialize(raw_connection, args = nil) ⇒ Connection

Initialize a new MiniSql::Postgres::Connection object

Parameters:

  • raw_connection (PG::Connection)

    an active connection to PG

  • deserializer_cache (MiniSql::DeserializerCache)

    a cache of field names to deserializer, can be nil

  • type_map (PG::TypeMap)

    a type mapper for all results returned, can be nil



52
53
54
55
56
57
58
# File 'lib/mini_sql/postgres/connection.rb', line 52

def initialize(raw_connection, args = nil)
  @raw_connection = raw_connection
  @deserializer_cache = (args && args[:deserializer_cache]) || self.class.default_deserializer_cache
  array_encoder = PG::TextEncoder::Array.new if args && args[:auto_encode_arrays]
  @param_encoder = (args && args[:param_encoder]) || InlineParamEncoder.new(self, array_encoder)
  @type_map = args && args[:type_map]
end

Instance Attribute Details

#deserializer_cacheObject (readonly)

Returns the value of attribute deserializer_cache.



6
7
8
# File 'lib/mini_sql/postgres/connection.rb', line 6

def deserializer_cache
  @deserializer_cache
end

#param_encoderObject (readonly)

Returns the value of attribute param_encoder.



6
7
8
# File 'lib/mini_sql/postgres/connection.rb', line 6

def param_encoder
  @param_encoder
end

#raw_connectionObject (readonly)

Returns the value of attribute raw_connection.



6
7
8
# File 'lib/mini_sql/postgres/connection.rb', line 6

def raw_connection
  @raw_connection
end

#type_mapObject (readonly)

Returns the value of attribute type_map.



60
61
62
# File 'lib/mini_sql/postgres/connection.rb', line 60

def type_map
  @type_map ||= self.class.type_map(raw_connection)
end

Class Method Details

.default_deserializer_cacheObject



8
9
10
# File 'lib/mini_sql/postgres/connection.rb', line 8

def self.default_deserializer_cache
  @deserializer_cache ||= DeserializerCache.new
end

.type_map(conn) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/mini_sql/postgres/connection.rb', line 12

def self.type_map(conn)
  @type_map ||=
    begin
      map = PG::BasicTypeMapForResults.new(conn)
      map.add_coder(MiniSql::Postgres::Coders::NumericCoder.new(name: "numeric", oid: 1700, format: 0))
      map.add_coder(MiniSql::Postgres::Coders::IPAddrCoder.new(name: "inet", oid: 869, format: 0))
      map.add_coder(MiniSql::Postgres::Coders::IPAddrCoder.new(name: "cidr", oid: 650, format: 0))
      map.add_coder(PG::TextDecoder::String.new(name: "tsvector", oid: 3614, format: 0))

      map.rm_coder(0, 1114)
      if defined? PG::TextDecoder::TimestampUtc
        # treat timestamp without zone as utc
        # new to PG 1.1
        map.add_coder(PG::TextDecoder::TimestampUtc.new(name: "timestamp", oid: 1114, format: 0))
      else
        map.add_coder(MiniSql::Postgres::Coders::TimestampUtc.new(name: "timestamp", oid: 1114, format: 0))
      end

      if defined? Pgvector::PG
        vector_oid =
          PG::BasicTypeRegistry::CoderMapsBundle
            .new(conn)
            .typenames_by_oid
            .find { |k, v| v == "vector" }
            &.first

        if !vector_oid.nil?
          map.add_coder(Pgvector::PG::TextDecoder::Vector.new(name: "vector", oid: vector_oid, format: 0))
          map.add_coder(Pgvector::PG::BinaryDecoder::Vector.new(name: "vector", oid: vector_oid, format: 1))
        end
      end
      map
    end
end

.typemapObject



24
25
26
27
28
29
30
# File 'lib/mini_sql/postgres_jdbc/connection.rb', line 24

def self.typemap
  @type_map ||= {
      "numeric" => NumericCoder.new,
      "inet" => IPAddrCoder.new,
      "cidr" => IPAddrCoder.new
  }
end

Instance Method Details

#escape_string(str) ⇒ Object



210
211
212
# File 'lib/mini_sql/postgres/connection.rb', line 210

def escape_string(str)
  raw_connection.escape_string(str)
end

#exec(sql, *params) ⇒ Object



195
196
197
198
199
200
# File 'lib/mini_sql/postgres/connection.rb', line 195

def exec(sql, *params)
  result = run(sql, params)
  result.cmd_tuples
ensure
  result.clear if result
end

#prepared(condition = true) ⇒ Object



64
65
66
67
68
69
70
# File 'lib/mini_sql/postgres/connection.rb', line 64

def prepared(condition = true)
  if condition
    @prepared ||= PreparedConnection.new(self)
  else
    self
  end
end

#query(sql, *params) ⇒ Object



113
114
115
116
117
118
119
# File 'lib/mini_sql/postgres/connection.rb', line 113

def query(sql, *params)
  result = run(sql, params)
  result.type_map = type_map
  deserializer_cache.materialize(result)
ensure
  result.clear if result
end

#query_array(sql, *params) ⇒ Object



105
106
107
108
109
110
111
# File 'lib/mini_sql/postgres/connection.rb', line 105

def query_array(sql, *params)
  result = run(sql, params)
  result.type_map = type_map
  result.values
ensure
  result.clear if result
end

#query_decorator(decorator, sql, *params) ⇒ Object



187
188
189
190
191
192
193
# File 'lib/mini_sql/postgres/connection.rb', line 187

def query_decorator(decorator, sql, *params)
  result = run(sql, params)
  result.type_map = type_map
  deserializer_cache.materialize(result, decorator)
ensure
  result.clear if result
end

#query_each(sql, *params) ⇒ Object

Raises:

  • (StandardError)


121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/mini_sql/postgres/connection.rb', line 121

def query_each(sql, *params)
  raise StandardError, "Please supply a block when calling query_each" if !block_given?
  if params && params.length > 0
    sql = param_encoder.encode(sql, *params)
  end

  raw_connection.send_query(sql)
  raw_connection.set_single_row_mode

  loop do
    result = raw_connection.get_result
    break if !result

    result.check

    if result.ntuples == 0
      # skip, this happens at the end when we get totals
    else
      materializer ||= deserializer_cache.materializer(result)
      result.type_map = type_map
      i = 0
      # technically we should only get 1 row here
      # but protect against future batching changes
      while i < result.ntuples
        yield materializer.materialize(result, i)
        i += 1
      end
    end

    result.clear
  end
end

#query_each_hash(sql, *params) ⇒ Object

Raises:

  • (StandardError)


154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/mini_sql/postgres/connection.rb', line 154

def query_each_hash(sql, *params)
  raise StandardError, "Please supply a block when calling query_each_hash" if !block_given?
  if params && params.length > 0
    sql = param_encoder.encode(sql, *params)
  end

  raw_connection.send_query(sql)
  raw_connection.set_single_row_mode

  loop do
    result = raw_connection.get_result
    break if !result

    result.check

    if result.ntuples == 0
      # skip, this happens at the end when we get totals
    else
      result.type_map = type_map
      i = 0

      # technically we should only get 1 row here
      # but protect against future batching changes
      while i < result.ntuples
        yield result[i]
        i += 1
      end
    end

    result.clear
  end
end

#query_hash(sql, *params) ⇒ Object



202
203
204
205
206
207
208
# File 'lib/mini_sql/postgres/connection.rb', line 202

def query_hash(sql, *params)
  result = run(sql, params)
  result.type_map = type_map
  result.to_a
ensure
  result.clear if result
end

#query_single(sql, *params) ⇒ Object

Returns a flat array containing all results. Note, if selecting multiple columns array will be flattened

Parameters:

  • sql (String)

    the query to run

  • params (Array or Hash)

    , params to apply to query

Returns:

  • (Object)

    a flat array containing all results



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/mini_sql/postgres/connection.rb', line 78

def query_single(sql, *params)
  result = run(sql, params)
  result.type_map = type_map
  if result.nfields == 1
    result.column_values(0)
  else
    tuples = result.ntuples
    fields = result.nfields

    array = []
    f = 0
    row = 0

    while row < tuples
      while f < fields
        array << result.getvalue(row, f)
        f += 1
      end
      f = 0
      row += 1
    end
    array
  end
ensure
  result.clear if result
end