class Sequel::Postgres::Database
Constants
- DATABASE_ERROR_CLASSES
Public Instance Methods
Convert given argument so that it can be used directly by pg. Currently, pg doesn’t handle fractional seconds in Time/DateTime or blobs with “0”. Only public for use by the adapter, shouldn’t be used by external code.
# File lib/sequel/adapters/postgres.rb 167 def bound_variable_arg(arg, conn) 168 case arg 169 when Sequel::SQL::Blob 170 {:value=>arg, :type=>17, :format=>1} 171 when DateTime, Time 172 literal(arg) 173 else 174 arg 175 end 176 end
Call a procedure with the given name and arguments. Returns a hash if the procedure returns a value, and nil otherwise. Example:
DB.call_procedure(:foo, 1, 2) # CALL foo(1, 2)
# File lib/sequel/adapters/postgres.rb 183 def call_procedure(name, *args) 184 dataset.send(:call_procedure, name, args) 185 end
Connects to the database. In addition to the standard database options, using the :encoding or :charset option changes the client encoding for the connection, :connect_timeout is a connection timeout in seconds, :sslmode sets whether postgres’s sslmode, and :notice_receiver handles server notices in a proc. :connect_timeout, :driver_options, :sslmode, and :notice_receiver are only supported if the pg driver is used.
# File lib/sequel/adapters/postgres.rb 194 def connect(server) 195 opts = server_opts(server) 196 if USES_PG 197 connection_params = { 198 :host => opts[:host], 199 :port => opts[:port], 200 :dbname => opts[:database], 201 :user => opts[:user], 202 :password => opts[:password], 203 :connect_timeout => opts[:connect_timeout] || 20, 204 :sslmode => opts[:sslmode], 205 :sslrootcert => opts[:sslrootcert] 206 }.delete_if { |key, value| blank_object?(value) } 207 connection_params.merge!(opts[:driver_options]) if opts[:driver_options] 208 conn = Adapter.connect(opts[:conn_str] || connection_params) 209 210 conn.instance_variable_set(:@prepared_statements, {}) 211 212 if receiver = opts[:notice_receiver] 213 conn.set_notice_receiver(&receiver) 214 end 215 else 216 unless typecast_value_boolean(@opts.fetch(:force_standard_strings, true)) 217 raise Error, "Cannot create connection using postgres-pr unless force_standard_strings is set" 218 end 219 220 conn = Adapter.connect( 221 (opts[:host] unless blank_object?(opts[:host])), 222 opts[:port] || 5432, 223 nil, '', 224 opts[:database], 225 opts[:user], 226 opts[:password] 227 ) 228 end 229 230 conn.instance_variable_set(:@db, self) 231 if USES_PG && conn.respond_to?(:type_map_for_queries=) && defined?(PG_QUERY_TYPE_MAP) 232 conn.type_map_for_queries = PG_QUERY_TYPE_MAP 233 end 234 235 if encoding = opts[:encoding] || opts[:charset] 236 if conn.respond_to?(:set_client_encoding) 237 conn.set_client_encoding(encoding) 238 else 239 conn.async_exec("set client_encoding to '#{encoding}'") 240 end 241 end 242 243 connection_configuration_sqls(opts).each{|sql| conn.execute(sql)} 244 conn 245 end
Always false, support was moved to pg_extended_date_support extension. Needs to stay defined here so that sequel_pg works.
# File lib/sequel/adapters/postgres.rb 249 def convert_infinite_timestamps 250 false 251 end
Enable pg_extended_date_support extension if symbol or string is given.
# File lib/sequel/adapters/postgres.rb 254 def convert_infinite_timestamps=(v) 255 case v 256 when Symbol, String, true 257 extension(:pg_extended_date_support) 258 self.convert_infinite_timestamps = v 259 end 260 end
copy_into
uses PostgreSQL’s +COPY FROM STDIN+ SQL
statement to do very fast inserts into a table using input preformatting in either CSV or PostgreSQL text format. This method is only supported if pg 0.14.0+ is the underlying ruby driver. This method should only be called if you want results returned to the client. If you are using +COPY FROM+ with a filename, you should just use run
instead of this method.
The following options are respected:
- :columns
-
The columns to insert into, with the same order as the columns in the input data. If this isn’t given, uses all columns in the table.
- :data
-
The data to copy to PostgreSQL, which should already be in CSV or PostgreSQL text format. This can be either a string, or any object that responds to each and yields string.
- :format
-
The format to use. text is the default, so this should be :csv or :binary.
- :options
-
An options
SQL
string to use, which should contain comma separated options. - :server
-
The server on which to run the query.
If a block is provided and :data option is not, this will yield to the block repeatedly. The block should return a string, or nil to signal that it is finished.
# File lib/sequel/adapters/postgres.rb 397 def copy_into(table, opts=OPTS) 398 data = opts[:data] 399 data = Array(data) if data.is_a?(String) 400 401 if defined?(yield) && data 402 raise Error, "Cannot provide both a :data option and a block to copy_into" 403 elsif !defined?(yield) && !data 404 raise Error, "Must provide either a :data option or a block to copy_into" 405 end 406 407 synchronize(opts[:server]) do |conn| 408 conn.execute(copy_into_sql(table, opts)) 409 begin 410 if defined?(yield) 411 while buf = yield 412 conn.put_copy_data(buf) 413 end 414 else 415 data.each{|buff| conn.put_copy_data(buff)} 416 end 417 rescue Exception => e 418 conn.put_copy_end("ruby exception occurred while copying data into PostgreSQL") 419 ensure 420 conn.put_copy_end unless e 421 while res = conn.get_result 422 raise e if e 423 check_database_errors{res.check} 424 end 425 end 426 end 427 end
copy_table
uses PostgreSQL’s +COPY TO STDOUT+ SQL
statement to return formatted results directly to the caller. This method is only supported if pg is the underlying ruby driver. This method should only be called if you want results returned to the client. If you are using +COPY TO+ with a filename, you should just use run
instead of this method.
The table argument supports the following types:
String
-
Uses the first argument directly as literal
SQL
. If you are using a version of PostgreSQL before 9.0, you will probably want to use a string if you are using any options at all, as the syntaxSequel
uses for options is only compatible with PostgreSQL 9.0+. This should be the full COPY statement passed to PostgreSQL, not just the SELECT query. If a string is given, the :format and :options options are ignored. Dataset
-
Uses a query instead of a table name when copying.
- other
-
Uses a table name (usually a symbol) when copying.
The following options are respected:
- :format
-
The format to use. text is the default, so this should be :csv or :binary.
- :options
-
An options
SQL
string to use, which should contain comma separated options. - :server
-
The server on which to run the query.
If a block is provided, the method continually yields to the block, one yield per row. If a block is not provided, a single string is returned with all of the data.
# File lib/sequel/adapters/postgres.rb 347 def copy_table(table, opts=OPTS) 348 synchronize(opts[:server]) do |conn| 349 conn.execute(copy_table_sql(table, opts)) 350 begin 351 if defined?(yield) 352 while buf = conn.get_copy_data 353 yield buf 354 end 355 b = nil 356 else 357 b = String.new 358 b << buf while buf = conn.get_copy_data 359 end 360 361 res = conn.get_last_result 362 if !res || res.result_status != 1 363 raise PG::NotAllCopyDataRetrieved, "Not all COPY data retrieved" 364 end 365 366 b 367 rescue => e 368 raise_error(e, :disconnect=>true) 369 ensure 370 if buf && !e 371 raise DatabaseDisconnectError, "disconnecting as a partial COPY may leave the connection in an unusable state" 372 end 373 end 374 end 375 end
# File lib/sequel/adapters/postgres.rb 262 def disconnect_connection(conn) 263 conn.finish 264 rescue PGError, IOError 265 nil 266 end
Return a hash of information about the related PGError (or Sequel::DatabaseError
that wraps a PGError), with the following entries (any of which may be nil
):
- :schema
-
The schema name related to the error
- :table
-
The table name related to the error
- :column
-
the column name related to the error
- :constraint
-
The constraint name related to the error
- :type
-
The datatype name related to the error
- :severity
-
The severity of the error (e.g. “ERROR”)
- :sql_state
-
The
SQL
state code related to the error - :message_primary
-
A single line message related to the error
- :message_detail
-
Any detail supplementing the primary message
- :message_hint
-
Possible suggestion about how to fix the problem
- :statement_position
-
Character offset in statement submitted by client where error occurred (starting at 1)
- :internal_position
-
Character offset in internal statement where error occurred (starting at 1)
- :internal_query
-
Text of internally-generated statement where error occurred
- :source_file
-
PostgreSQL source file where the error occurred
- :source_line
-
Line number of PostgreSQL source file where the error occurred
- :source_function
-
Function in PostgreSQL source file where the error occurred
This requires a PostgreSQL 9.3+ server and 9.3+ client library, and ruby-pg 0.16.0+ to be supported.
# File lib/sequel/adapters/postgres.rb 291 def error_info(e) 292 e = e.wrapped_exception if e.is_a?(DatabaseError) 293 r = e.result 294 { 295 :schema => r.error_field(::PG::PG_DIAG_SCHEMA_NAME), 296 :table => r.error_field(::PG::PG_DIAG_TABLE_NAME), 297 :column => r.error_field(::PG::PG_DIAG_COLUMN_NAME), 298 :constraint => r.error_field(::PG::PG_DIAG_CONSTRAINT_NAME), 299 :type => r.error_field(::PG::PG_DIAG_DATATYPE_NAME), 300 :severity => r.error_field(::PG::PG_DIAG_SEVERITY), 301 :sql_state => r.error_field(::PG::PG_DIAG_SQLSTATE), 302 :message_primary => r.error_field(::PG::PG_DIAG_MESSAGE_PRIMARY), 303 :message_detail => r.error_field(::PG::PG_DIAG_MESSAGE_DETAIL), 304 :message_hint => r.error_field(::PG::PG_DIAG_MESSAGE_HINT), 305 :statement_position => r.error_field(::PG::PG_DIAG_STATEMENT_POSITION), 306 :internal_position => r.error_field(::PG::PG_DIAG_INTERNAL_POSITION), 307 :internal_query => r.error_field(::PG::PG_DIAG_INTERNAL_QUERY), 308 :source_file => r.error_field(::PG::PG_DIAG_SOURCE_FILE), 309 :source_line => r.error_field(::PG::PG_DIAG_SOURCE_LINE), 310 :source_function => r.error_field(::PG::PG_DIAG_SOURCE_FUNCTION) 311 } 312 end
# File lib/sequel/adapters/postgres.rb 315 def execute(sql, opts=OPTS, &block) 316 synchronize(opts[:server]){|conn| check_database_errors{_execute(conn, sql, opts, &block)}} 317 end
Listens on the given channel (or multiple channels if channel is an array), waiting for notifications. After a notification is received, or the timeout has passed, stops listening to the channel. Options:
- :after_listen
-
An object that responds to
call
that is called with the underlying connection after the LISTEN statement is sent, but before the connection starts waiting for notifications. - :loop
-
Whether to continually wait for notifications, instead of just waiting for a single notification. If this option is given, a block must be provided. If this object responds to
call
, it is called with the underlying connection after each notification is received (after the block is called). If a :timeout option is used, and a callable object is given, the object will also be called if the timeout expires. If :loop is used and you want to stop listening, you can either break from inside the block given tolisten
, or you can throw :stop from inside the :loop object’s call method or the block. - :server
-
The server on which to listen, if the sharding support is being used.
- :timeout
-
How long to wait for a notification, in seconds (can provide a float value for fractional seconds). If this object responds to
call
, it will be called and should return the number of seconds to wait. If the loop option is also specified, the object will be called on each iteration to obtain a new timeout value. If not given or nil, waits indefinitely.
This method is only supported if pg is used as the underlying ruby driver. It returns the channel the notification was sent to (as a string), unless :loop was used, in which case it returns nil. If a block is given, it is yielded 3 arguments:
-
the channel the notification was sent to (as a string)
-
the backend pid of the notifier (as an integer),
-
and the payload of the notification (as a string or nil).
# File lib/sequel/adapters/postgres.rb 452 def listen(channels, opts=OPTS, &block) 453 check_database_errors do 454 synchronize(opts[:server]) do |conn| 455 begin 456 channels = Array(channels) 457 channels.each do |channel| 458 sql = "LISTEN ".dup 459 dataset.send(:identifier_append, sql, channel) 460 conn.execute(sql) 461 end 462 opts[:after_listen].call(conn) if opts[:after_listen] 463 timeout = opts[:timeout] 464 if timeout 465 timeout_block = timeout.respond_to?(:call) ? timeout : proc{timeout} 466 end 467 468 if l = opts[:loop] 469 raise Error, 'calling #listen with :loop requires a block' unless block 470 loop_call = l.respond_to?(:call) 471 catch(:stop) do 472 while true 473 t = timeout_block ? [timeout_block.call] : [] 474 conn.wait_for_notify(*t, &block) 475 l.call(conn) if loop_call 476 end 477 end 478 nil 479 else 480 t = timeout_block ? [timeout_block.call] : [] 481 conn.wait_for_notify(*t, &block) 482 end 483 ensure 484 conn.execute("UNLISTEN *") 485 end 486 end 487 end 488 end
Private Instance Methods
Execute the given SQL
string or prepared statement on the connection object.
# File lib/sequel/adapters/postgres.rb 494 def _execute(conn, sql, opts, &block) 495 if sql.is_a?(Symbol) 496 execute_prepared_statement(conn, sql, opts, &block) 497 else 498 conn.execute(sql, opts[:arguments], &block) 499 end 500 end
Execute the prepared statement name with the given arguments on the connection.
# File lib/sequel/adapters/postgres.rb 503 def _execute_prepared_statement(conn, ps_name, args, opts) 504 conn.exec_prepared(ps_name, args) 505 end
Add the primary_keys and primary_key_sequences instance variables, so we can get the correct return values for inserted rows.
# File lib/sequel/adapters/postgres.rb 509 def adapter_initialize 510 @use_iso_date_format = typecast_value_boolean(@opts.fetch(:use_iso_date_format, true)) 511 initialize_postgres_adapter 512 add_conversion_proc(17, method(:unescape_bytea)) if USES_PG 513 add_conversion_proc(1082, TYPE_TRANSLATOR_DATE) if @use_iso_date_format 514 self.convert_infinite_timestamps = @opts[:convert_infinite_timestamps] 515 end
Convert exceptions raised from the block into DatabaseErrors.
# File lib/sequel/adapters/postgres.rb 518 def check_database_errors 519 yield 520 rescue => e 521 raise_error(e, :classes=>database_error_classes) 522 end
Set the DateStyle to ISO if configured, for faster date parsing.
Sequel::Postgres::DatabaseMethods#connection_configuration_sqls
# File lib/sequel/adapters/postgres.rb 525 def connection_configuration_sqls(opts=@opts) 526 sqls = super 527 sqls << "SET DateStyle = 'ISO'" if @use_iso_date_format 528 sqls 529 end
# File lib/sequel/adapters/postgres.rb 538 def database_error_classes 539 DATABASE_ERROR_CLASSES 540 end
# File lib/sequel/adapters/postgres.rb 548 def database_exception_sqlstate(exception, opts) 549 if exception.respond_to?(:result) && (result = exception.result) 550 result.error_field(PGresult::PG_DIAG_SQLSTATE) 551 end 552 end
# File lib/sequel/adapters/postgres.rb 554 def dataset_class_default 555 Dataset 556 end
Sequel::Database#disconnect_error?
# File lib/sequel/adapters/postgres.rb 542 def disconnect_error?(exception, opts) 543 super || 544 Adapter::DISCONNECT_ERROR_CLASSES.any?{|klass| exception.is_a?(klass)} || 545 exception.message =~ Adapter::DISCONNECT_ERROR_RE 546 end
Execute the prepared statement with the given name on an available connection, using the given args. If the connection has not prepared a statement with the given name yet, prepare it. If the connection has prepared a statement with the same name and different SQL
, deallocate that statement first and then prepare this statement. If a block is given, yield the result, otherwise, return the number of rows changed.
# File lib/sequel/adapters/postgres.rb 565 def execute_prepared_statement(conn, name, opts=OPTS, &block) 566 ps = prepared_statement(name) 567 sql = ps.prepared_sql 568 ps_name = name.to_s 569 570 if args = opts[:arguments] 571 args = args.map{|arg| bound_variable_arg(arg, conn)} 572 end 573 574 unless conn.prepared_statements[ps_name] == sql 575 conn.execute("DEALLOCATE #{ps_name}") if conn.prepared_statements.include?(ps_name) 576 conn.check_disconnect_errors{log_connection_yield("PREPARE #{ps_name} AS #{sql}", conn){conn.prepare(ps_name, sql)}} 577 conn.prepared_statements[ps_name] = sql 578 end 579 580 log_sql = "EXECUTE #{ps_name}" 581 if ps.log_sql 582 log_sql += " (" 583 log_sql << sql 584 log_sql << ")" 585 end 586 587 q = conn.check_disconnect_errors{log_connection_yield(log_sql, conn, args){_execute_prepared_statement(conn, ps_name, args, opts)}} 588 begin 589 defined?(yield) ? yield(q) : q.cmd_tuples 590 ensure 591 q.clear if q && q.respond_to?(:clear) 592 end 593 end
Don’t log, since logging is done by the underlying connection.
# File lib/sequel/adapters/postgres.rb 596 def log_connection_execute(conn, sql) 597 conn.execute(sql) 598 end
Sequel::Database#rollback_transaction
# File lib/sequel/adapters/postgres.rb 600 def rollback_transaction(conn, opts=OPTS) 601 super unless conn.transaction_status == 0 602 end
# File lib/sequel/adapters/postgres.rb 532 def unescape_bytea(s) 533 ::Sequel::SQL::Blob.new(Adapter.unescape_bytea(s)) 534 end