Skip to content
Newer
Older
100644 820 lines (706 sloc) 26.6 KB
db045db @dhh Initial
dhh authored Nov 24, 2004
1 require 'active_record/connection_adapters/abstract_adapter'
54b7e78 @tenderlove Database adapters use a statement pool.
tenderlove authored Sep 6, 2011
2 require 'active_record/connection_adapters/statement_pool'
9fd3bde @tenderlove many of the OIDs mapped and implemented
tenderlove authored Feb 2, 2012
3 require 'active_record/connection_adapters/postgresql/oid'
232d222 @etehtsea Modularize postgresql adapter
etehtsea authored Aug 26, 2012
4 require 'active_record/connection_adapters/postgresql/cast'
4544d2b Moves column dump specific code to a module included in AbstractAdapter
Dan McClain authored Aug 19, 2012
5 require 'active_record/connection_adapters/postgresql/array_parser'
232d222 @etehtsea Modularize postgresql adapter
etehtsea authored Aug 25, 2012
6 require 'active_record/connection_adapters/postgresql/quoting'
7 require 'active_record/connection_adapters/postgresql/schema_statements'
8 require 'active_record/connection_adapters/postgresql/database_statements'
9 require 'active_record/connection_adapters/postgresql/referential_integrity'
fd39847 @tenderlove prepared statements can be disabled
tenderlove authored Feb 21, 2012
10 require 'arel/visitors/bind_visitor'
3d19b35 @tenderlove fetch result row arrays from pg in C and return early if there are no…
tenderlove authored Apr 22, 2011
11
12 # Make sure we're using pg high enough for PGResult#values
13 gem 'pg', '~> 0.11'
df9abfa @tenderlove require pg when this adapter is loaded
tenderlove authored Sep 29, 2010
14 require 'pg'
db045db @dhh Initial
dhh authored Nov 24, 2004
15
0e1c651 Removes NetAddr dependency
Dan McClain authored May 8, 2012
16 require 'ipaddr'
17
db045db @dhh Initial
dhh authored Nov 24, 2004
18 module ActiveRecord
dae7b65 @jonleighton Support establishing connection on ActiveRecord::Model.
jonleighton authored Dec 28, 2011
19 module ConnectionHandling
db045db @dhh Initial
dhh authored Nov 24, 2004
20 # Establishes a connection to the database that's used by all Active Record objects
6af7192 @jonleighton I herd you like modules.
jonleighton authored Dec 18, 2011
21 def postgresql_connection(config) # :nodoc:
f63fff6 @tenderlove delete reaping frequency from the db config
tenderlove authored Jan 5, 2012
22 conn_params = config.symbolize_keys
db045db @dhh Initial
dhh authored Nov 24, 2004
23
8ee6406 @larskanis Postgresql: Allow setting of any libpq connection parameters
larskanis authored Jan 3, 2012
24 # Forward any unused config params to PGconn.connect.
f63fff6 @tenderlove delete reaping frequency from the db config
tenderlove authored Jan 5, 2012
25 [:statement_limit, :encoding, :min_messages, :schema_search_path,
925f6bd @rafaelfranca PGconn doesn't accepts :checkout_timeout option.
rafaelfranca authored May 23, 2012
26 :schema_order, :adapter, :pool, :checkout_timeout, :template,
97d06e8 @sodabrew Session variables for mysql, mysql2, and postgresql adapters can be set
sodabrew authored Nov 27, 2012
27 :reaping_frequency, :insert_returning, :variables].each do |key|
f63fff6 @tenderlove delete reaping frequency from the db config
tenderlove authored Jan 5, 2012
28 conn_params.delete key
29 end
92a3c48 @larskanis Postgresql: restore previous behaviour regarding to nil values in con…
larskanis authored Jan 5, 2012
30 conn_params.delete_if { |k,v| v.nil? }
8ee6406 @larskanis Postgresql: Allow setting of any libpq connection parameters
larskanis authored Jan 3, 2012
31
32 # Map ActiveRecords param names to PGs.
33 conn_params[:user] = conn_params.delete(:username) if conn_params[:username]
34 conn_params[:dbname] = conn_params.delete(:database) if conn_params[:database]
db045db @dhh Initial
dhh authored Nov 24, 2004
35
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobS…
Marcel Molina authored Nov 8, 2007
36 # The postgres drivers don't allow the creation of an unconnected PGconn object,
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
37 # so just pass a nil connection object for the time being.
8ee6406 @larskanis Postgresql: Allow setting of any libpq connection parameters
larskanis authored Jan 3, 2012
38 ConnectionAdapters::PostgreSQLAdapter.new(nil, logger, conn_params, config)
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
39 end
40 end
c699a3e @dhh Added option :schema_order to the PostgreSQL adapter to support the u…
dhh authored Feb 23, 2005
41
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
42 module ConnectionAdapters
43 # PostgreSQL-specific extensions to column definitions in a table.
44 class PostgreSQLColumn < Column #:nodoc:
4544d2b Moves column dump specific code to a module included in AbstractAdapter
Dan McClain authored Aug 19, 2012
45 attr_accessor :array
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
46 # Instantiates a new PostgreSQL column definition in a table.
c50cb4a @tenderlove PG column consults oid types when typecasting
tenderlove authored Feb 10, 2012
47 def initialize(name, default, oid_type, sql_type = nil, null = true)
48 @oid_type = oid_type
4544d2b Moves column dump specific code to a module included in AbstractAdapter
Dan McClain authored Aug 19, 2012
49 if sql_type =~ /\[\]$/
50 @array = true
51 super(name, self.class.extract_value_from_default(default), sql_type[0..sql_type.length - 3], null)
52 else
53 @array = false
54 super(name, self.class.extract_value_from_default(default), sql_type, null)
55 end
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
56 end
5821096 Multiple fixes and optimizations in PostgreSQL adapter, allowing ruby…
Tobias Lütke authored Apr 4, 2006
57
61355c0 @tenderlove clearing up many warnings, removing unnecessary regular expresion com…
tenderlove authored Apr 10, 2010
58 # :stopdoc:
59 class << self
232d222 @etehtsea Modularize postgresql adapter
etehtsea authored Aug 25, 2012
60 include ConnectionAdapters::PostgreSQLColumn::Cast
4544d2b Moves column dump specific code to a module included in AbstractAdapter
Dan McClain authored Aug 19, 2012
61 include ConnectionAdapters::PostgreSQLColumn::ArrayParser
232d222 @etehtsea Modularize postgresql adapter
etehtsea authored Aug 25, 2012
62 attr_accessor :money_precision
61355c0 @tenderlove clearing up many warnings, removing unnecessary regular expresion com…
tenderlove authored Apr 11, 2010
63 end
64 # :startdoc:
65
a9a1270 @tenderlove fixing indentation, moving class methods together
tenderlove authored Feb 9, 2012
66 # Extracts the value from a PostgreSQL column default definition.
67 def self.extract_value_from_default(default)
68 # This is a performance optimization for Ruby 1.9.2 in development.
69 # If the value is nil, we return nil straight away without checking
70 # the regular expressions. If we check each regular expression,
71 # Regexp#=== will call NilClass#to_str, which will trigger
72 # method_missing (defined by whiny nil in ActiveSupport) which
73 # makes this method very very slow.
74 return default unless default
75
76 case default
77 # Numeric types
78 when /\A\(?(-?\d+(\.\d*)?\)?)\z/
79 $1
8cb7bc8 @tenderlove pg columns should understand the hstore type
tenderlove authored Dec 19, 2011
80 # Character types
2da85ed @arturopie #7914 get default value when type uses schema name
arturopie authored Oct 12, 2012
81 when /\A\(?'(.*)'::.*\b(?:character varying|bpchar|text)\z/m
a9a1270 @tenderlove fixing indentation, moving class methods together
tenderlove authored Feb 9, 2012
82 $1
8cb7bc8 @tenderlove pg columns should understand the hstore type
tenderlove authored Dec 20, 2011
83 # Binary data types
a9a1270 @tenderlove fixing indentation, moving class methods together
tenderlove authored Feb 9, 2012
84 when /\A'(.*)'::bytea\z/m
85 $1
8cb7bc8 @tenderlove pg columns should understand the hstore type
tenderlove authored Dec 20, 2011
86 # Date/time types
a9a1270 @tenderlove fixing indentation, moving class methods together
tenderlove authored Feb 9, 2012
87 when /\A'(.+)'::(?:time(?:stamp)? with(?:out)? time zone|date)\z/
88 $1
89 when /\A'(.*)'::interval\z/
90 $1
91 # Boolean type
92 when 'true'
93 true
94 when 'false'
95 false
8cb7bc8 @tenderlove pg columns should understand the hstore type
tenderlove authored Dec 20, 2011
96 # Geometric types
a9a1270 @tenderlove fixing indentation, moving class methods together
tenderlove authored Feb 9, 2012
97 when /\A'(.*)'::(?:point|line|lseg|box|"?path"?|polygon|circle)\z/
98 $1
8cb7bc8 @tenderlove pg columns should understand the hstore type
tenderlove authored Dec 20, 2011
99 # Network address types
a9a1270 @tenderlove fixing indentation, moving class methods together
tenderlove authored Feb 9, 2012
100 when /\A'(.*)'::(?:cidr|inet|macaddr)\z/
101 $1
102 # Bit string types
103 when /\AB'(.*)'::"?bit(?: varying)?"?\z/
104 $1
8cb7bc8 @tenderlove pg columns should understand the hstore type
tenderlove authored Dec 20, 2011
105 # XML type
a9a1270 @tenderlove fixing indentation, moving class methods together
tenderlove authored Feb 9, 2012
106 when /\A'(.*)'::xml\z/m
107 $1
8cb7bc8 @tenderlove pg columns should understand the hstore type
tenderlove authored Dec 20, 2011
108 # Arrays
a9a1270 @tenderlove fixing indentation, moving class methods together
tenderlove authored Feb 9, 2012
109 when /\A'(.*)'::"?\D+"?\[\]\z/
110 $1
f7b915b @tenderlove Merge branch 'joelhoffman-postgres_schema_builder' into instance_reader
tenderlove authored Feb 10, 2012
111 # Hstore
112 when /\A'(.*)'::hstore\z/
113 $1
3b516b5 @guedes ActiveRecord support to PostgreSQL 9.2 JSON type
guedes authored Sep 5, 2012
114 # JSON
115 when /\A'(.*)'::json\z/
116 $1
9a4a095 @le0pard AR supporting new intrange data type on PostgreSQL >= 9.2
le0pard authored Dec 16, 2012
117 # int4range, int8range
118 when /\A'(.*)'::int(4|8)range\z/
119 $1
8cb7bc8 @tenderlove pg columns should understand the hstore type
tenderlove authored Dec 20, 2011
120 # Object identifier types
a9a1270 @tenderlove fixing indentation, moving class methods together
tenderlove authored Feb 9, 2012
121 when /\A-?\d+\z/
122 $1
8cb7bc8 @tenderlove pg columns should understand the hstore type
tenderlove authored Dec 20, 2011
123 else
a9a1270 @tenderlove fixing indentation, moving class methods together
tenderlove authored Feb 9, 2012
124 # Anything else is blank, some user type, or some function
125 # and we can't know the value of that, so return nil.
126 nil
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
127 end
a9a1270 @tenderlove fixing indentation, moving class methods together
tenderlove authored Feb 9, 2012
128 end
8885b2d @miloops Refactor to calculations. Migration's versions are string not integer…
miloops authored May 6, 2009
129
c50cb4a @tenderlove PG column consults oid types when typecasting
tenderlove authored Feb 11, 2012
130 def type_cast(value)
131 return if value.nil?
132 return super if encoded?
133
134 @oid_type.type_cast value
135 end
136
a9a1270 @tenderlove fixing indentation, moving class methods together
tenderlove authored Feb 9, 2012
137 private
232d222 @etehtsea Modularize postgresql adapter
etehtsea authored Aug 25, 2012
138
139 def extract_limit(sql_type)
140 case sql_type
141 when /^bigint/i; 8
142 when /^smallint/i; 2
143 when /^timestamp/i; nil
144 else super
145 end
a9a1270 @tenderlove fixing indentation, moving class methods together
tenderlove authored Feb 9, 2012
146 end
147
232d222 @etehtsea Modularize postgresql adapter
etehtsea authored Aug 25, 2012
148 # Extracts the scale from PostgreSQL-specific data types.
149 def extract_scale(sql_type)
150 # Money type has a fixed scale of 2.
151 sql_type =~ /^money/ ? 2 : super
152 end
a9a1270 @tenderlove fixing indentation, moving class methods together
tenderlove authored Feb 9, 2012
153
232d222 @etehtsea Modularize postgresql adapter
etehtsea authored Aug 25, 2012
154 # Extracts the precision from PostgreSQL-specific data types.
155 def extract_precision(sql_type)
156 if sql_type == 'money'
157 self.class.money_precision
158 elsif sql_type =~ /timestamp/i
159 $1.to_i if sql_type =~ /\((\d+)\)/
160 else
161 super
162 end
a9a1270 @tenderlove fixing indentation, moving class methods together
tenderlove authored Feb 9, 2012
163 end
164
232d222 @etehtsea Modularize postgresql adapter
etehtsea authored Aug 25, 2012
165 # Maps PostgreSQL-specific data types to logical Rails types.
166 def simplified_type(field_type)
167 case field_type
168 # Numeric and monetary types
169 when /^(?:real|double precision)$/
170 :float
171 # Monetary types
172 when 'money'
173 :decimal
174 when 'hstore'
175 :hstore
176 # Network address types
177 when 'inet'
178 :inet
179 when 'cidr'
180 :cidr
181 when 'macaddr'
182 :macaddr
183 # Character types
184 when /^(?:character varying|bpchar)(?:\(\d+\))?$/
185 :string
186 # Binary data types
187 when 'bytea'
188 :binary
189 # Date/time types
190 when /^timestamp with(?:out)? time zone$/
191 :datetime
319482d @senny postgres, map scaled intervals to string datatype (#7518)
senny authored Sep 5, 2012
192 when /^interval(?:|\(\d+\))$/
232d222 @etehtsea Modularize postgresql adapter
etehtsea authored Aug 25, 2012
193 :string
194 # Geometric types
195 when /^(?:point|line|lseg|box|"?path"?|polygon|circle)$/
196 :string
197 # Bit strings
198 when /^bit(?: varying)?(?:\(\d+\))?$/
199 :string
200 # XML type
201 when 'xml'
202 :xml
203 # tsvector type
204 when 'tsvector'
205 :tsvector
206 # Arrays
207 when /^\D+\[\]$/
208 :string
209 # Object identifier types
210 when 'oid'
211 :integer
212 # UUID type
213 when 'uuid'
214 :uuid
9a4a095 @le0pard AR supporting new intrange data type on PostgreSQL >= 9.2
le0pard authored Dec 16, 2012
215 # JSON type
216 when 'json'
217 :json
218 # int4range, int8range types
219 when 'int4range', 'int8range'
220 :intrange
232d222 @etehtsea Modularize postgresql adapter
etehtsea authored Aug 25, 2012
221 # Small and big integer types
222 when /^(?:small|big)int$/
223 :integer
224 # Pass through all types that are not specific to PostgreSQL.
225 else
226 super
227 end
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
228 end
db045db @dhh Initial
dhh authored Nov 24, 2004
229 end
230
8ee6406 @larskanis Postgresql: Allow setting of any libpq connection parameters
larskanis authored Jan 3, 2012
231 # The PostgreSQL adapter works with the native C (https://bitbucket.org/ged/ruby-pg) driver.
1dc0b2a @dhh Added documentation for database adapters to visible RDoc
dhh authored Feb 23, 2005
232 #
233 # Options:
234 #
8ee6406 @larskanis Postgresql: Allow setting of any libpq connection parameters
larskanis authored Jan 3, 2012
235 # * <tt>:host</tt> - Defaults to a Unix-domain socket in /tmp. On machines without Unix-domain sockets,
236 # the default is to connect to localhost.
dc4eec1 @lifo Merge docrails:
lifo authored May 9, 2008
237 # * <tt>:port</tt> - Defaults to 5432.
8ee6406 @larskanis Postgresql: Allow setting of any libpq connection parameters
larskanis authored Jan 3, 2012
238 # * <tt>:username</tt> - Defaults to be the same as the operating system name of the user running the application.
239 # * <tt>:password</tt> - Password to be used if the server demands password authentication.
240 # * <tt>:database</tt> - Defaults to be the same as the user name.
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored Aug 14, 2010
241 # * <tt>:schema_search_path</tt> - An optional schema search path for the connection given
0034b78 @smartinez87 Remove extra white spaces on ActiveRecord docs.
smartinez87 authored May 23, 2011
242 # as a string of comma-separated schema names. This is backward-compatible with the <tt>:schema_order</tt> option.
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored Aug 14, 2010
243 # * <tt>:encoding</tt> - An optional client encoding that is used in a <tt>SET client_encoding TO
1ce40ca ensuring that description does not exceed 100 columns
Neeraj Singh authored Aug 2, 2010
244 # <encoding></tt> call on the connection.
b451de0 @spastorino Deletes trailing whitespaces (over text files only find * -type f -ex…
spastorino authored Aug 14, 2010
245 # * <tt>:min_messages</tt> - An optional client min messages that is used in a
1ce40ca ensuring that description does not exceed 100 columns
Neeraj Singh authored Aug 2, 2010
246 # <tt>SET client_min_messages TO <min_messages></tt> call on the connection.
97d06e8 @sodabrew Session variables for mysql, mysql2, and postgresql adapters can be set
sodabrew authored Nov 27, 2012
247 # * <tt>:variables</tt> - An optional hash of additional parameters that
248 # will be used in <tt>SET SESSION key = val</tt> calls on the connection.
28fc893 @AvnerCohen Fixed unclosing tag
AvnerCohen authored Oct 9, 2012
249 # * <tt>:insert_returning</tt> - An optional boolean to control the use or <tt>RETURNING</tt> for <tt>INSERT</tt> statements
cd6ddc8 @dougcole refactor configuration of insert_returning
dougcole authored Apr 7, 2012
250 # defaults to true.
8ee6406 @larskanis Postgresql: Allow setting of any libpq connection parameters
larskanis authored Jan 3, 2012
251 #
252 # Any further options are used as connection parameters to libpq. See
253 # http://www.postgresql.org/docs/9.1/static/libpq-connect.html for the
254 # list of parameters.
255 #
256 # In addition, default connection parameters of libpq can be set per environment variables.
257 # See http://www.postgresql.org/docs/9.1/static/libpq-envars.html .
1dc0b2a @dhh Added documentation for database adapters to visible RDoc
dhh authored Feb 23, 2005
258 class PostgreSQLAdapter < AbstractAdapter
4544d2b Moves column dump specific code to a module included in AbstractAdapter
Dan McClain authored Aug 19, 2012
259 class ColumnDefinition < ActiveRecord::ConnectionAdapters::ColumnDefinition
260 attr_accessor :array
261 end
262
b297911 @tenderlove use inheritence to deal with custom methods
tenderlove authored Sep 29, 2010
263 class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition
264 def xml(*args)
265 options = args.extract_options!
266 column(args[0], 'xml', options)
267 end
714b4a8 Added tsvector Datatype Support
Benjamin Fritsch authored Apr 26, 2011
268
269 def tsvector(*args)
270 options = args.extract_options!
271 column(args[0], 'tsvector', options)
272 end
8cb7bc8 @tenderlove pg columns should understand the hstore type
tenderlove authored Dec 20, 2011
273
274 def hstore(name, options = {})
275 column(name, 'hstore', options)
276 end
f7b8fbd Adds migration and schema dump support for INET, CIDR, and MACADDR
Dan Seaver authored May 5, 2012
277
278 def inet(name, options = {})
279 column(name, 'inet', options)
280 end
281
282 def cidr(name, options = {})
283 column(name, 'cidr', options)
284 end
285
286 def macaddr(name, options = {})
287 column(name, 'macaddr', options)
288 end
12e9a75 @etehtsea Add uuid type support to PostgreSQL adapter
etehtsea authored Jun 12, 2012
289
290 def uuid(name, options = {})
291 column(name, 'uuid', options)
292 end
3b516b5 @guedes ActiveRecord support to PostgreSQL 9.2 JSON type
guedes authored Sep 5, 2012
293
294 def json(name, options = {})
295 column(name, 'json', options)
296 end
4544d2b Moves column dump specific code to a module included in AbstractAdapter
Dan McClain authored Aug 19, 2012
297
9a4a095 @le0pard AR supporting new intrange data type on PostgreSQL >= 9.2
le0pard authored Dec 16, 2012
298 def intrange(name, options = {})
299 column(name, 'intrange', options)
300 end
301
4544d2b Moves column dump specific code to a module included in AbstractAdapter
Dan McClain authored Aug 19, 2012
302 def column(name, type = nil, options = {})
303 super
304 column = self[name]
305 column.array = options[:array]
306
307 self
308 end
309
310 private
311
312 def new_column_definition(base, name, type)
313 definition = ColumnDefinition.new base, name, type
314 @columns << definition
315 @columns_hash[name] = definition
316 definition
317 end
b297911 @tenderlove use inheritence to deal with custom methods
tenderlove authored Sep 29, 2010
318 end
319
df9abfa @tenderlove require pg when this adapter is loaded
tenderlove authored Sep 29, 2010
320 ADAPTER_NAME = 'PostgreSQL'
def594b @jeremy Don't append limit to primary key column definition. Freeze some cons…
jeremy authored Jun 8, 2008
321
322 NATIVE_DATABASE_TYPES = {
232d222 @etehtsea Modularize postgresql adapter
etehtsea authored Aug 25, 2012
323 primary_key: "serial primary key",
324 string: { name: "character varying", limit: 255 },
325 text: { name: "text" },
326 integer: { name: "integer" },
327 float: { name: "float" },
328 decimal: { name: "decimal" },
329 datetime: { name: "timestamp" },
330 timestamp: { name: "timestamp" },
331 time: { name: "time" },
332 date: { name: "date" },
333 binary: { name: "bytea" },
334 boolean: { name: "boolean" },
335 xml: { name: "xml" },
336 tsvector: { name: "tsvector" },
337 hstore: { name: "hstore" },
338 inet: { name: "inet" },
339 cidr: { name: "cidr" },
340 macaddr: { name: "macaddr" },
3b516b5 @guedes ActiveRecord support to PostgreSQL 9.2 JSON type
guedes authored Sep 5, 2012
341 uuid: { name: "uuid" },
9a4a095 @le0pard AR supporting new intrange data type on PostgreSQL >= 9.2
le0pard authored Dec 16, 2012
342 json: { name: "json" },
343 intrange: { name: "int4range" }
def594b @jeremy Don't append limit to primary key column definition. Freeze some cons…
jeremy authored Jun 9, 2008
344 }
345
232d222 @etehtsea Modularize postgresql adapter
etehtsea authored Aug 25, 2012
346 include Quoting
347 include ReferentialIntegrity
348 include SchemaStatements
349 include DatabaseStatements
350
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
351 # Returns 'PostgreSQL' as adapter name for identification purposes.
b3df959 @dhh Refactored the AbstractAdapter to be a lot less scary. Cleaned up the…
dhh authored Sep 25, 2005
352 def adapter_name
def594b @jeremy Don't append limit to primary key column definition. Freeze some cons…
jeremy authored Jun 9, 2008
353 ADAPTER_NAME
b3df959 @dhh Refactored the AbstractAdapter to be a lot less scary. Cleaned up the…
dhh authored Sep 25, 2005
354 end
355
4544d2b Moves column dump specific code to a module included in AbstractAdapter
Dan McClain authored Aug 19, 2012
356 # Adds `:array` option to the default set provided by the
357 # AbstractAdapter
358 def prepare_column_options(column, types)
359 spec = super
360 spec[:array] = 'true' if column.respond_to?(:array) && column.array
361 spec
362 end
363
364 # Adds `:array` as a valid migration key
365 def migration_keys
366 super + [:array]
367 end
368
00e9cbd @smartinez87 Have a more connection specific rdoc for +supports_statement_cache?+
smartinez87 authored Apr 22, 2011
369 # Returns +true+, since this connection adapter supports prepared statement
370 # caching.
104d0b2 @tenderlove adding backwards compatibility for non-prepare statement handling dri…
tenderlove authored Oct 22, 2010
371 def supports_statement_cache?
372 true
373 end
374
69dcd45 @vjebelev AR changes to support creating ordered (asc, desc) indexes
vjebelev authored Nov 4, 2011
375 def supports_index_sort_order?
376 true
377 end
378
d70e023 @mhfs Added where option to add_index to support postgresql partial indices
mhfs authored Feb 9, 2012
379 def supports_partial_index?
380 true
381 end
382
392eeec @jonleighton Support for specifying transaction isolation level
jonleighton authored Sep 21, 2012
383 def supports_transaction_isolation?
384 true
385 end
386
54b7e78 @tenderlove Database adapters use a statement pool.
tenderlove authored Sep 6, 2011
387 class StatementPool < ConnectionAdapters::StatementPool
388 def initialize(connection, max)
389 super
390 @counter = 0
834d429 @tenderlove LRU should cache per process in postgresql. fixes #1339
tenderlove authored Sep 7, 2011
391 @cache = Hash.new { |h,pid| h[pid] = {} }
54b7e78 @tenderlove Database adapters use a statement pool.
tenderlove authored Sep 6, 2011
392 end
393
834d429 @tenderlove LRU should cache per process in postgresql. fixes #1339
tenderlove authored Sep 7, 2011
394 def each(&block); cache.each(&block); end
395 def key?(key); cache.key?(key); end
396 def [](key); cache[key]; end
397 def length; cache.length; end
54b7e78 @tenderlove Database adapters use a statement pool.
tenderlove authored Sep 6, 2011
398
399 def next_key
400 "a#{@counter + 1}"
401 end
402
403 def []=(sql, key)
834d429 @tenderlove LRU should cache per process in postgresql. fixes #1339
tenderlove authored Sep 7, 2011
404 while @max <= cache.size
405 dealloc(cache.shift.last)
54b7e78 @tenderlove Database adapters use a statement pool.
tenderlove authored Sep 6, 2011
406 end
407 @counter += 1
834d429 @tenderlove LRU should cache per process in postgresql. fixes #1339
tenderlove authored Sep 7, 2011
408 cache[sql] = key
54b7e78 @tenderlove Database adapters use a statement pool.
tenderlove authored Sep 6, 2011
409 end
410
411 def clear
834d429 @tenderlove LRU should cache per process in postgresql. fixes #1339
tenderlove authored Sep 7, 2011
412 cache.each_value do |stmt_key|
54b7e78 @tenderlove Database adapters use a statement pool.
tenderlove authored Sep 6, 2011
413 dealloc stmt_key
414 end
834d429 @tenderlove LRU should cache per process in postgresql. fixes #1339
tenderlove authored Sep 7, 2011
415 cache.clear
54b7e78 @tenderlove Database adapters use a statement pool.
tenderlove authored Sep 6, 2011
416 end
417
6a28c51 @tenderlove reset prepared statement when schema changes imapact statement result…
tenderlove authored Oct 18, 2011
418 def delete(sql_key)
419 dealloc cache[sql_key]
420 cache.delete sql_key
421 end
422
54b7e78 @tenderlove Database adapters use a statement pool.
tenderlove authored Sep 6, 2011
423 private
834d429 @tenderlove LRU should cache per process in postgresql. fixes #1339
tenderlove authored Sep 7, 2011
424
232d222 @etehtsea Modularize postgresql adapter
etehtsea authored Aug 25, 2012
425 def cache
426 @cache[Process.pid]
427 end
ee9d9fb @tenderlove Merge pull request #3258 from ileitch/3-1-stable
tenderlove authored Oct 20, 2011
428
232d222 @etehtsea Modularize postgresql adapter
etehtsea authored Aug 25, 2012
429 def dealloc(key)
430 @connection.query "DEALLOCATE #{key}" if connection_active?
431 end
432
433 def connection_active?
434 @connection.status == PGconn::CONNECTION_OK
435 rescue PGError
436 false
437 end
54b7e78 @tenderlove Database adapters use a statement pool.
tenderlove authored Sep 6, 2011
438 end
439
fd39847 @tenderlove prepared statements can be disabled
tenderlove authored Feb 21, 2012
440 class BindSubstitution < Arel::Visitors::PostgreSQL # :nodoc:
441 include Arel::Visitors::BindVisitor
442 end
443
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
444 # Initializes and connects a PostgreSQL adapter.
445 def initialize(connection, logger, connection_parameters, config)
e8f664d @jeremy MySQL, PostgreSQL: reconnect! also reconfigures the connection. Other…
jeremy authored Nov 22, 2005
446 super(connection, logger)
fd39847 @tenderlove prepared statements can be disabled
tenderlove authored Feb 21, 2012
447
448 if config.fetch(:prepared_statements) { true }
449 @visitor = Arel::Visitors::PostgreSQL.new self
450 else
451 @visitor = BindSubstitution.new self
452 end
453
454 connection_parameters.delete :prepared_statements
455
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
456 @connection_parameters, @config = connection_parameters, config
821f2d5 @jeremy PostgreSQL: don't use async_exec and async_query with postgres-pr. Cl…
jeremy authored Mar 6, 2007
457
7a7c608 @spastorino Your original TIME ZONE value on PostgreSQL is correctly restored now…
spastorino authored Jun 23, 2010
458 # @local_tz is initialized as nil to avoid warnings when connect tries to use it
459 @local_tz = nil
36150c9 @tenderlove Let's initialize instance variables in the postgres adapter.
tenderlove authored Jul 14, 2010
460 @table_alias_length = nil
461
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
462 connect
54b7e78 @tenderlove Database adapters use a statement pool.
tenderlove authored Sep 6, 2011
463 @statements = StatementPool.new @connection,
464 config.fetch(:statement_limit) { 1000 }
35dba50 @tenderlove community support for pg < 8.2 has ended, so we can drop support for …
tenderlove authored Apr 10, 2011
465
466 if postgresql_version < 80200
467 raise "Your version of PostgreSQL (#{postgresql_version}) is too old, please upgrade!"
468 end
469
fa6cda5 @tenderlove dynamically populate casting objects via the pg_type table
tenderlove authored Feb 10, 2012
470 initialize_type_map
90a3714 @tenderlove properly name schema queries for the logger
tenderlove authored Apr 8, 2011
471 @local_tz = execute('SHOW TIME ZONE', 'SCHEMA').first["TimeZone"]
cd6ddc8 @dougcole refactor configuration of insert_returning
dougcole authored Apr 8, 2012
472 @use_insert_returning = @config.key?(:insert_returning) ? @config[:insert_returning] : true
e8f664d @jeremy MySQL, PostgreSQL: reconnect! also reconfigures the connection. Other…
jeremy authored Nov 22, 2005
473 end
474
df70b9d @fxn copy-edits 0e2644c
fxn authored Apr 23, 2011
475 # Clears the prepared statements cache.
ffb9991 @tenderlove initial exec() method is working in pg adapter
tenderlove authored Oct 15, 2010
476 def clear_cache!
477 @statements.clear
478 end
479
44b6470 @jeremy r3032@asus: jeremy | 2005-11-12 23:16:52 -0800
jeremy authored Nov 13, 2005
480 # Is this connection alive and ready for queries?
481 def active?
4dacac3 @steveklabnik Properly discover a connection is closed in postgresql_adapter
steveklabnik authored May 24, 2012
482 @connection.query 'SELECT 1'
483 true
0eea560 @tenderlove requring pg ~> 0.11, so remove conditional code for supporting older …
tenderlove authored Apr 29, 2011
484 rescue PGError
15aa6e0 @jeremy r4644@asus: jeremy | 2006-06-16 14:57:03 -0700
jeremy authored Jun 19, 2006
485 false
44b6470 @jeremy r3032@asus: jeremy | 2005-11-12 23:16:52 -0800
jeremy authored Nov 13, 2005
486 end
487
488 # Close then reopen the connection.
489 def reconnect!
02f5655 @jonleighton Ensure disconnecting or reconnecting resets the transaction state
jonleighton authored Sep 14, 2012
490 super
0eea560 @tenderlove requring pg ~> 0.11, so remove conditional code for supporting older …
tenderlove authored Apr 29, 2011
491 @connection.reset
492 configure_connection
44b6470 @jeremy r3032@asus: jeremy | 2005-11-12 23:16:52 -0800
jeremy authored Nov 13, 2005
493 end
15aa6e0 @jeremy r4644@asus: jeremy | 2006-06-16 14:57:03 -0700
jeremy authored Jun 19, 2006
494
ffb9991 @tenderlove initial exec() method is working in pg adapter
tenderlove authored Oct 15, 2010
495 def reset!
496 clear_cache!
497 super
498 end
499
02ee200 @smartinez87 Added docs for #disconnect! on adapters
smartinez87 authored Apr 22, 2011
500 # Disconnects from the database if already connected. Otherwise, this
501 # method does nothing.
6bd8e35 @jeremy ActiveRecord::Base.remove_connection explicitly closes database conne…
jeremy authored Feb 26, 2006
502 def disconnect!
02f5655 @jonleighton Ensure disconnecting or reconnecting resets the transaction state
jonleighton authored Sep 14, 2012
503 super
6bd8e35 @jeremy ActiveRecord::Base.remove_connection explicitly closes database conne…
jeremy authored Feb 26, 2006
504 @connection.close rescue nil
505 end
44b6470 @jeremy r3032@asus: jeremy | 2005-11-12 23:16:52 -0800
jeremy authored Nov 13, 2005
506
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
507 def native_database_types #:nodoc:
def594b @jeremy Don't append limit to primary key column definition. Freeze some cons…
jeremy authored Jun 9, 2008
508 NATIVE_DATABASE_TYPES
4160b51 @dhh Added new Migrations framework for describing schema transformations …
dhh authored Jul 4, 2005
509 end
15aa6e0 @jeremy r4644@asus: jeremy | 2006-06-16 14:57:03 -0700
jeremy authored Jun 19, 2006
510
868fb38 @smartinez87 Make this docs more consistent with the rest of the docs present
smartinez87 authored Apr 22, 2011
511 # Returns true, since this connection adapter supports migrations.
4160b51 @dhh Added new Migrations framework for describing schema transformations …
dhh authored Jul 4, 2005
512 def supports_migrations?
513 true
15aa6e0 @jeremy r4644@asus: jeremy | 2006-06-16 14:57:03 -0700
jeremy authored Jun 19, 2006
514 end
515
f17159b @fxn edit pass: the names of Rails components have a space, ie, "Active Re…
fxn authored Jun 14, 2010
516 # Does PostgreSQL support finding primary key on non-Active Record tables?
f060221 @bellmyer raises exception (ActiveRecord::ConfigurationError with message) on h…
bellmyer authored Feb 26, 2009
517 def supports_primary_key? #:nodoc:
518 true
519 end
520
dac80f7 @jeremy PostgreSQL: use standard-conforming strings if possible
jeremy authored Apr 24, 2010
521 # Enable standard-conforming strings if available.
522 def set_standard_conforming_strings
523 old, self.client_min_messages = client_min_messages, 'panic'
90a3714 @tenderlove properly name schema queries for the logger
tenderlove authored Apr 9, 2011
524 execute('SET standard_conforming_strings = on', 'SCHEMA') rescue nil
dac80f7 @jeremy PostgreSQL: use standard-conforming strings if possible
jeremy authored Apr 24, 2010
525 ensure
526 self.client_min_messages = old
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
527 end
528
03bf727 @jeremy PostgreSQL: use 'INSERT ... RETURNING id' for 8.2 and later.
jeremy authored Jun 10, 2008
529 def supports_insert_with_returning?
35dba50 @tenderlove community support for pg < 8.2 has ended, so we can drop support for …
tenderlove authored Apr 11, 2011
530 true
03bf727 @jeremy PostgreSQL: use 'INSERT ... RETURNING id' for 8.2 and later.
jeremy authored Jun 11, 2008
531 end
532
707ee0e @tarmo Made migrations transactional for PostgreSQL [#834 state:resolved]
tarmo authored Aug 22, 2008
533 def supports_ddl_transactions?
534 true
535 end
8885b2d @miloops Refactor to calculations. Migration's versions are string not integer…
miloops authored May 6, 2009
536
868fb38 @smartinez87 Make this docs more consistent with the rest of the docs present
smartinez87 authored Apr 22, 2011
537 # Returns true, since this connection adapter supports savepoints.
885c11b @FooBarWidget Make SQLite3 pass the unit tests for savepoints.
FooBarWidget authored Oct 9, 2008
538 def supports_savepoints?
539 true
540 end
707ee0e @tarmo Made migrations transactional for PostgreSQL [#834 state:resolved]
tarmo authored Aug 22, 2008
541
0306f82 @fxn implements automatic EXPLAIN logging for slow queries
fxn authored Dec 2, 2011
542 # Returns true.
543 def supports_explain?
544 true
545 end
546
35dba50 @tenderlove community support for pg < 8.2 has ended, so we can drop support for …
tenderlove authored Apr 11, 2011
547 # Returns the configured supported identifier length supported by PostgreSQL
263479b @technoweenie Add AbstractAdapter#table_alias_for to create table aliases according…
technoweenie authored Mar 18, 2006
548 def table_alias_length
576d700 @kennyj Fix logs name consistency.
kennyj authored May 19, 2012
549 @table_alias_length ||= query('SHOW max_identifier_length', 'SCHEMA')[0][0].to_i
263479b @technoweenie Add AbstractAdapter#table_alias_for to create table aliases according…
technoweenie authored Mar 18, 2006
550 end
2c6b6e2 @technoweenie automatically add primary key to #select_limited_ids_list order by cl…
technoweenie authored Oct 13, 2006
551
4544d2b Moves column dump specific code to a module included in AbstractAdapter
Dan McClain authored Aug 19, 2012
552 def add_column_options!(sql, options)
553 if options[:array] || options[:column].try(:array)
554 sql << '[]'
555 end
556 super
557 end
558
9d9aed4 @tenderlove add a session authorization setter to the pg connection
tenderlove authored Oct 21, 2010
559 # Set the authorized user for this session
560 def session_auth=(user)
02128d6 @tenderlove setting the authorized session clears the statement cache
tenderlove authored Oct 21, 2010
561 clear_cache!
0f45f23 @tenderlove renaming exec in the PG adapter
tenderlove authored Nov 5, 2010
562 exec_query "SET SESSION AUTHORIZATION #{user}"
9d9aed4 @tenderlove add a session authorization setter to the pg connection
tenderlove authored Oct 21, 2010
563 end
564
9991f0f @dasch Refactor PostgreSQLAdapter a bit
dasch authored Jul 8, 2011
565 module Utils
a982443 @dasch Make #extract_schema_and_table an instance method in Utils
dasch authored Jul 9, 2011
566 extend self
567
9991f0f @dasch Refactor PostgreSQLAdapter a bit
dasch authored Jul 8, 2011
568 # Returns an array of <tt>[schema_name, table_name]</tt> extracted from +name+.
569 # +schema_name+ is nil if not specified in +name+.
570 # +schema_name+ and +table_name+ exclude surrounding quotes (regardless of whether provided in +name+)
571 # +name+ supports the range of schema/table references understood by PostgreSQL, for example:
572 #
573 # * <tt>table_name</tt>
574 # * <tt>"table.name"</tt>
575 # * <tt>schema_name.table_name</tt>
576 # * <tt>schema_name."table.name"</tt>
577 # * <tt>"schema.name"."table name"</tt>
a982443 @dasch Make #extract_schema_and_table an instance method in Utils
dasch authored Jul 9, 2011
578 def extract_schema_and_table(name)
9991f0f @dasch Refactor PostgreSQLAdapter a bit
dasch authored Jul 8, 2011
579 table, schema = name.scan(/[^".\s]+|"[^"]*"/)[0..1].collect{|m| m.gsub(/(^"|"$)/,'') }.reverse
580 [schema, table]
581 end
582 end
583
3a0d081 @dougcole pick better names and add a little documentation
dougcole authored Apr 1, 2012
584 def use_insert_returning?
585 @use_insert_returning
f09bb33 @dougcole add use_returning as a postgresql connection config
dougcole authored Mar 31, 2012
586 end
587
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
588 protected
232d222 @etehtsea Modularize postgresql adapter
etehtsea authored Aug 25, 2012
589
4d04641 @smartinez87 Fix #postgresql_version docs
smartinez87 authored Apr 22, 2011
590 # Returns the version of the connected PostgreSQL server.
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
591 def postgresql_version
0eea560 @tenderlove requring pg ~> 0.11, so remove conditional code for supporting older …
tenderlove authored Apr 29, 2011
592 @connection.server_version
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
593 end
594
2fe2813 @kennyj Fix a problem of translate_exception method in Japanese.
kennyj authored May 20, 2012
595 # See http://www.postgresql.org/docs/9.1/static/errcodes-appendix.html
596 FOREIGN_KEY_VIOLATION = "23503"
597 UNIQUE_VIOLATION = "23505"
598
53a3eaa @mschuerig Translate adapter errors that indicate a violated uniqueness constrai…
mschuerig authored Apr 5, 2009
599 def translate_exception(exception, message)
0d63cda Don't crash exception translation w/ nil result attribute.
Steve Jorgensen authored May 21, 2012
600 case exception.result.try(:error_field, PGresult::PG_DIAG_SQLSTATE)
2fe2813 @kennyj Fix a problem of translate_exception method in Japanese.
kennyj authored May 19, 2012
601 when UNIQUE_VIOLATION
b5dfdc7 @NZKoz Make sure the wrapped exceptions also have the original exception ava…
NZKoz authored Jun 26, 2009
602 RecordNotUnique.new(message, exception)
2fe2813 @kennyj Fix a problem of translate_exception method in Japanese.
kennyj authored May 19, 2012
603 when FOREIGN_KEY_VIOLATION
b5dfdc7 @NZKoz Make sure the wrapped exceptions also have the original exception ava…
NZKoz authored Jun 26, 2009
604 InvalidForeignKey.new(message, exception)
53a3eaa @mschuerig Translate adapter errors that indicate a violated uniqueness constrai…
mschuerig authored Apr 4, 2009
605 else
606 super
607 end
608 end
609
db045db @dhh Initial
dhh authored Nov 24, 2004
610 private
fa6cda5 @tenderlove dynamically populate casting objects via the pg_type table
tenderlove authored Feb 10, 2012
611
232d222 @etehtsea Modularize postgresql adapter
etehtsea authored Aug 25, 2012
612 def initialize_type_map
4544d2b Moves column dump specific code to a module included in AbstractAdapter
Dan McClain authored Aug 19, 2012
613 result = execute('SELECT oid, typname, typelem, typdelim, typinput FROM pg_type', 'SCHEMA')
232d222 @etehtsea Modularize postgresql adapter
etehtsea authored Aug 25, 2012
614 leaves, nodes = result.partition { |row| row['typelem'] == '0' }
fa6cda5 @tenderlove dynamically populate casting objects via the pg_type table
tenderlove authored Feb 10, 2012
615
232d222 @etehtsea Modularize postgresql adapter
etehtsea authored Aug 25, 2012
616 # populate the leaf nodes
617 leaves.find_all { |row| OID.registered_type? row['typname'] }.each do |row|
618 OID::TYPE_MAP[row['oid'].to_i] = OID::NAMES[row['typname']]
619 end
620
4544d2b Moves column dump specific code to a module included in AbstractAdapter
Dan McClain authored Aug 19, 2012
621 arrays, nodes = nodes.partition { |row| row['typinput'] == 'array_in' }
622
232d222 @etehtsea Modularize postgresql adapter
etehtsea authored Aug 25, 2012
623 # populate composite types
624 nodes.find_all { |row| OID::TYPE_MAP.key? row['typelem'].to_i }.each do |row|
625 vector = OID::Vector.new row['typdelim'], OID::TYPE_MAP[row['typelem'].to_i]
626 OID::TYPE_MAP[row['oid'].to_i] = vector
627 end
4544d2b Moves column dump specific code to a module included in AbstractAdapter
Dan McClain authored Aug 19, 2012
628
629 # populate array types
630 arrays.find_all { |row| OID::TYPE_MAP.key? row['typelem'].to_i }.each do |row|
631 array = OID::Array.new OID::TYPE_MAP[row['typelem'].to_i]
632 OID::TYPE_MAP[row['oid'].to_i] = array
633 end
fa6cda5 @tenderlove dynamically populate casting objects via the pg_type table
tenderlove authored Feb 10, 2012
634 end
635
6a28c51 @tenderlove reset prepared statement when schema changes imapact statement result…
tenderlove authored Oct 18, 2011
636 FEATURE_NOT_SUPPORTED = "0A000" # :nodoc:
637
019c263 @tardate apply private method indentation convention
tardate authored Jun 10, 2011
638 def exec_no_cache(sql, binds)
639 @connection.async_exec(sql)
1741bbe @tenderlove avoiding statement cache if there are no bind values
tenderlove authored Oct 21, 2010
640 end
f1df6b2 @tenderlove postgresql supports prepare statement deletes
tenderlove authored Apr 28, 2011
641
019c263 @tardate apply private method indentation convention
tardate authored Jun 10, 2011
642 def exec_cache(sql, binds)
6a28c51 @tenderlove reset prepared statement when schema changes imapact statement result…
tenderlove authored Oct 18, 2011
643 begin
644 stmt_key = prepare_statement sql
645
646 # Clear the queue
647 @connection.get_last_result
648 @connection.send_query_prepared(stmt_key, binds.map { |col, val|
649 type_cast(val, col)
650 })
651 @connection.block
652 @connection.get_last_result
653 rescue PGError => e
654 # Get the PG code for the failure. Annoyingly, the code for
655 # prepared statements whose return value may have changed is
656 # FEATURE_NOT_SUPPORTED. Check here for more details:
657 # http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/cache/plancache.c#l573
aaff1a4 @tenderlove database connections are automatically established after forking.
tenderlove authored Feb 16, 2012
658 begin
659 code = e.result.result_error_field(PGresult::PG_DIAG_SQLSTATE)
660 rescue
661 raise e
662 end
6a28c51 @tenderlove reset prepared statement when schema changes imapact statement result…
tenderlove authored Oct 18, 2011
663 if FEATURE_NOT_SUPPORTED == code
664 @statements.delete sql_key(sql)
665 retry
666 else
667 raise e
668 end
669 end
670 end
671
672 # Returns the statement identifier for the client side cache
673 # of statements
674 def sql_key(sql)
675 "#{schema_search_path}-#{sql}"
676 end
677
678 # Prepare the statement if it hasn't been prepared, return
679 # the statement key.
680 def prepare_statement(sql)
681 sql_key = sql_key(sql)
cfc95d8 @Juanmcuello Use the schema_search_path in prepared statements.
Juanmcuello authored Oct 5, 2011
682 unless @statements.key? sql_key
54b7e78 @tenderlove Database adapters use a statement pool.
tenderlove authored Sep 6, 2011
683 nextkey = @statements.next_key
019c263 @tardate apply private method indentation convention
tardate authored Jun 10, 2011
684 @connection.prepare nextkey, sql
cfc95d8 @Juanmcuello Use the schema_search_path in prepared statements.
Juanmcuello authored Oct 5, 2011
685 @statements[sql_key] = nextkey
019c263 @tardate apply private method indentation convention
tardate authored Jun 10, 2011
686 end
6a28c51 @tenderlove reset prepared statement when schema changes imapact statement result…
tenderlove authored Oct 18, 2011
687 @statements[sql_key]
019c263 @tardate apply private method indentation convention
tardate authored Jun 10, 2011
688 end
1741bbe @tenderlove avoiding statement cache if there are no bind values
tenderlove authored Oct 21, 2010
689
0432d15 @lifo Merge with docrails.
lifo authored Jul 16, 2008
690 # The internal PostgreSQL identifier of the money data type.
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
691 MONEY_COLUMN_TYPE_OID = 790 #:nodoc:
bc35631 @tenderlove use constants instead of magic numbers. meow
tenderlove authored Jul 13, 2010
692 # The internal PostgreSQL identifier of the BYTEA data type.
693 BYTEA_COLUMN_TYPE_OID = 17 #:nodoc:
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
694
695 # Connects to a PostgreSQL server and sets up the adapter depending on the
696 # connected server's characteristics.
697 def connect
8ee6406 @larskanis Postgresql: Allow setting of any libpq connection parameters
larskanis authored Jan 3, 2012
698 @connection = PGconn.connect(@connection_parameters)
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
699
700 # Money type has a fixed precision of 10 in PostgreSQL 8.2 and below, and as of
701 # PostgreSQL 8.3 it has a fixed precision of 19. PostgreSQLColumn.extract_precision
702 # should know about this but can't detect it there, so deal with it here.
dac80f7 @jeremy PostgreSQL: use standard-conforming strings if possible
jeremy authored Apr 24, 2010
703 PostgreSQLColumn.money_precision = (postgresql_version >= 80300) ? 19 : 10
704
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
705 configure_connection
706 end
707
c5b652f @jackc PostgreSQLAdapter: set time_zone to UTC when Base.default_timezone ==…
jackc authored Jan 23, 2010
708 # Configures the encoding, verbosity, schema search path, and time zone of the connection.
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
709 # This is called by #connect and should not be called manually.
e8f664d @jeremy MySQL, PostgreSQL: reconnect! also reconfigures the connection. Other…
jeremy authored Nov 22, 2005
710 def configure_connection
711 if @config[:encoding]
0eea560 @tenderlove requring pg ~> 0.11, so remove conditional code for supporting older …
tenderlove authored Apr 29, 2011
712 @connection.set_client_encoding(@config[:encoding])
e8f664d @jeremy MySQL, PostgreSQL: reconnect! also reconfigures the connection. Other…
jeremy authored Nov 22, 2005
713 end
052e415 @kennyj Change minimum (default) log level in PostgreSQL to warning.
kennyj authored Jun 16, 2012
714 self.client_min_messages = @config[:min_messages] || 'warning'
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
715 self.schema_search_path = @config[:schema_search_path] || @config[:schema_order]
dac80f7 @jeremy PostgreSQL: use standard-conforming strings if possible
jeremy authored Apr 24, 2010
716
717 # Use standard-conforming strings if available so we don't have to do the E'...' dance.
718 set_standard_conforming_strings
719
f17159b @fxn edit pass: the names of Rails components have a space, ie, "Active Re…
fxn authored Jun 14, 2010
720 # If using Active Record's time zone support configure the connection to return
c5b652f @jackc PostgreSQLAdapter: set time_zone to UTC when Base.default_timezone ==…
jackc authored Jan 24, 2010
721 # TIMESTAMP WITH ZONE types in UTC.
97d06e8 @sodabrew Session variables for mysql, mysql2, and postgresql adapters can be set
sodabrew authored Nov 27, 2012
722 # (SET TIME ZONE does not use an equals sign like other SET variables)
bf6661c @tenderlove setting the timezone in postgres to whatever ruby thinks the timezone…
tenderlove authored Jun 17, 2010
723 if ActiveRecord::Base.default_timezone == :utc
90a3714 @tenderlove properly name schema queries for the logger
tenderlove authored Apr 9, 2011
724 execute("SET time zone 'UTC'", 'SCHEMA')
7a7c608 @spastorino Your original TIME ZONE value on PostgreSQL is correctly restored now…
spastorino authored Jun 24, 2010
725 elsif @local_tz
90a3714 @tenderlove properly name schema queries for the logger
tenderlove authored Apr 9, 2011
726 execute("SET time zone '#{@local_tz}'", 'SCHEMA')
bf6661c @tenderlove setting the timezone in postgres to whatever ruby thinks the timezone…
tenderlove authored Jun 17, 2010
727 end
97d06e8 @sodabrew Session variables for mysql, mysql2, and postgresql adapters can be set
sodabrew authored Nov 27, 2012
728
729 # SET statements from :variables config hash
730 # http://www.postgresql.org/docs/8.3/static/sql-set.html
731 variables = @config[:variables] || {}
732 variables.map do |k, v|
733 if v == ':default' || v == :default
734 # Sets the value to the global or compile default
735 execute("SET SESSION #{k.to_s} TO DEFAULT", 'SCHEMA')
736 elsif !v.nil?
737 execute("SET SESSION #{k.to_s} TO #{quote(v)}", 'SCHEMA')
738 end
739 end
e8f664d @jeremy MySQL, PostgreSQL: reconnect! also reconfigures the connection. Other…
jeremy authored Nov 22, 2005
740 end
741
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
742 # Returns the current ID of a table's sequence.
3378d77 @tenderlove use prepared statements to fetch the last insert id
tenderlove authored Mar 21, 2011
743 def last_insert_id(sequence_name) #:nodoc:
f09bb33 @dougcole add use_returning as a postgresql connection config
dougcole authored Mar 31, 2012
744 Integer(last_insert_id_value(sequence_name))
745 end
746
20615e7 @dougcole refactor
dougcole authored Mar 31, 2012
747 def last_insert_id_value(sequence_name)
748 last_insert_id_result(sequence_name).rows.first.first
749 end
750
751 def last_insert_id_result(sequence_name) #:nodoc:
6f3489c @evtuhovich Remove prepared statement from system query in postgresql adapter
evtuhovich authored Apr 17, 2012
752 exec_query("SELECT currval('#{sequence_name}')", 'SQL')
db045db @dhh Initial
dhh authored Nov 24, 2004
753 end
754
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
755 # Executes a SELECT query and returns the results, performing any data type
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobS…
Marcel Molina authored Nov 8, 2007
756 # conversions that are required to be performed here instead of in PostgreSQLColumn.
43bbb25 @tenderlove bind substitution is working properly
tenderlove authored Oct 15, 2010
757 def select(sql, name = nil, binds = [])
40ce682 @tenderlove made the result set object act more like an array
tenderlove authored Jan 26, 2012
758 exec_query(sql, name, binds)
30fb7b8 @jeremy connection.select_rows 'sql' returns an array (rows) of arrays (field…
jeremy authored Sep 16, 2007
759 end
760
761 def select_raw(sql, name = nil)
d0bd3b5 @jeremy Return PostgreSQL columns in the order they are declared #1374 (perlg…
jeremy authored Jun 12, 2005
762 res = execute(sql, name)
9a947af @jeremy PostgreSQL: support server versions 7.4 through 8.0 and the ruby-pg d…
jeremy authored Feb 22, 2008
763 results = result_as_array(res)
8521cdf @tenderlove PostgreSQLAdapter#select_raw fields and results are empty even if ntu…
tenderlove authored Jul 12, 2010
764 fields = res.fields
15aa6e0 @jeremy r4644@asus: jeremy | 2006-06-16 14:57:03 -0700
jeremy authored Jun 19, 2006
765 res.clear
2aed63e @tenderlove our method is modifying the original array, so refactor to use destru…
tenderlove authored Jul 12, 2010
766 return fields, results
e2da98e Back out of [2548].
Marcel Molina authored Oct 14, 2005
767 end
768
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
769 # Returns the list of a table's column names, data types, and default values.
1fde44b @jeremy r1278@iwill: jeremy | 2005-06-12 05:11:48 -0700
jeremy authored Jun 12, 2005
770 #
771 # The underlying query is roughly:
772 # SELECT column.name, column.type, default.value
773 # FROM column LEFT JOIN default
774 # ON column.table_id = default.table_id
775 # AND column.num = default.column_num
776 # WHERE column.table_id = get_table_id('table_name')
777 # AND column.num > 0
778 # AND NOT column.is_dropped
779 # ORDER BY column.num
780 #
781 # If the table name is not prefixed with a schema, the database will
782 # take the first match from the schema search path.
783 #
784 # Query implementation notes:
785 # - format_type includes the column size constraint, e.g. varchar(50)
786 # - ::regclass is a function that gives the id for a table name
29b0707 @NZKoz Improve performance and functionality of the postgresql adapter. Closes
NZKoz authored Aug 16, 2007
787 def column_definitions(table_name) #:nodoc:
90a3714 @tenderlove properly name schema queries for the logger
tenderlove authored Apr 9, 2011
788 exec_query(<<-end_sql, 'SCHEMA').rows
40475cf @arturopie #7914 Using a better way to get the defaults from db.
arturopie authored Oct 13, 2012
789 SELECT a.attname, format_type(a.atttypid, a.atttypmod),
790 pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
4544d2b Moves column dump specific code to a module included in AbstractAdapter
Dan McClain authored Aug 19, 2012
791 FROM pg_attribute a LEFT JOIN pg_attrdef d
792 ON a.attrelid = d.adrelid AND a.attnum = d.adnum
793 WHERE a.attrelid = '#{quote_table_name(table_name)}'::regclass
794 AND a.attnum > 0 AND NOT a.attisdropped
795 ORDER BY a.attnum
1fde44b @jeremy r1278@iwill: jeremy | 2005-06-12 05:11:48 -0700
jeremy authored Jun 12, 2005
796 end_sql
db045db @dhh Initial
dhh authored Nov 24, 2004
797 end
70de8e6 @maxlapshin Support multiple schemas in table names for postgresql [#390 state:re…
maxlapshin authored Apr 4, 2009
798
799 def extract_pg_identifier_from_name(name)
e7d860c @tenderlove create fewer objects, call fewer methods in extract_pg_identifier_fro…
tenderlove authored Oct 4, 2010
800 match_data = name.start_with?('"') ? name.match(/\"([^\"]+)\"/) : name.match(/([^\.]+)/)
70de8e6 @maxlapshin Support multiple schemas in table names for postgresql [#390 state:re…
maxlapshin authored Apr 4, 2009
801
802 if match_data
e7d860c @tenderlove create fewer objects, call fewer methods in extract_pg_identifier_fro…
tenderlove authored Oct 4, 2010
803 rest = name[match_data[0].length, name.length]
804 rest = rest[1, rest.length] if rest.start_with? "."
89925e8 @josevalim Revert "Use any instead of length"
josevalim authored Nov 28, 2011
805 [match_data[1], (rest.length > 0 ? rest : nil)]
70de8e6 @maxlapshin Support multiple schemas in table names for postgresql [#390 state:re…
maxlapshin authored Apr 4, 2009
806 end
807 end
b297911 @tenderlove use inheritence to deal with custom methods
tenderlove authored Sep 29, 2010
808
5c7f8c9 @tardate Improve PostgreSQL adapter schema-awareness
tardate authored Jun 9, 2011
809 def extract_table_ref_from_insert_sql(sql)
810 sql[/into\s+([^\(]*).*values\s*\(/i]
811 $1.strip if $1
812 end
813
019c263 @tardate apply private method indentation convention
tardate authored Jun 10, 2011
814 def table_definition
815 TableDefinition.new(self)
816 end
db045db @dhh Initial
dhh authored Nov 24, 2004
817 end
818 end
819 end
Something went wrong with that request. Please try again.