Class | Sequel::Postgres::Database |
In: |
lib/sequel/adapters/postgres.rb
|
Parent: | Sequel::Database |
INFINITE_TIMESTAMP_STRINGS | = | ['infinity'.freeze, '-infinity'.freeze].freeze |
INFINITE_DATETIME_VALUES | = | ([PLUS_INFINITY, MINUS_INFINITY] + INFINITE_TIMESTAMP_STRINGS).freeze |
DATABASE_ERROR_CLASSES | = | [PGError].freeze |
convert_infinite_timestamps | [R] | Whether infinite timestamps/dates should be converted on retrieval. By default, no conversion is done, so an error is raised if you attempt to retrieve an infinite timestamp/date. You can set this to :nil to convert to nil, :string to leave as a string, or :float to convert to an infinite float. |
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, line 167 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
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, line 185 185: def connect(server) 186: opts = server_opts(server) 187: if USES_PG 188: connection_params = { 189: :host => opts[:host], 190: :port => opts[:port] || 5432, 191: :dbname => opts[:database], 192: :user => opts[:user], 193: :password => opts[:password], 194: :connect_timeout => opts[:connect_timeout] || 20, 195: :sslmode => opts[:sslmode], 196: :sslrootcert => opts[:sslrootcert] 197: }.delete_if { |key, value| blank_object?(value) } 198: connection_params.merge!(opts[:driver_options]) if opts[:driver_options] 199: conn = Adapter.connect(connection_params) 200: 201: conn.instance_variable_set(:@prepared_statements, {}) 202: 203: if receiver = opts[:notice_receiver] 204: conn.set_notice_receiver(&receiver) 205: end 206: else 207: unless typecast_value_boolean(@opts.fetch(:force_standard_strings, true)) 208: raise Error, "Cannot create connection using postgres-pr unless force_standard_strings is set" 209: end 210: 211: conn = Adapter.connect( 212: (opts[:host] unless blank_object?(opts[:host])), 213: opts[:port] || 5432, 214: nil, '', 215: opts[:database], 216: opts[:user], 217: opts[:password] 218: ) 219: end 220: 221: conn.instance_variable_set(:@db, self) 222: 223: if encoding = opts[:encoding] || opts[:charset] 224: if conn.respond_to?(:set_client_encoding) 225: conn.set_client_encoding(encoding) 226: else 227: conn.async_exec("set client_encoding to '#{encoding}'") 228: end 229: end 230: 231: connection_configuration_sqls.each{|sql| conn.execute(sql)} 232: conn 233: end
Set whether to allow infinite timestamps/dates. Make sure the conversion proc for date reflects that setting.
# File lib/sequel/adapters/postgres.rb, line 237 237: def convert_infinite_timestamps=(v) 238: @convert_infinite_timestamps = case v 239: when Symbol 240: v 241: when 'nil' 242: :nil 243: when 'string' 244: :string 245: when 'float' 246: :float 247: when String 248: typecast_value_boolean(v) 249: else 250: false 251: end 252: 253: pr = old_pr = @use_iso_date_format ? TYPE_TRANSLATOR.method(:date) : Sequel.method(:string_to_date) 254: if v 255: pr = lambda do |val| 256: case val 257: when *INFINITE_TIMESTAMP_STRINGS 258: infinite_timestamp_value(val) 259: else 260: old_pr.call(val) 261: end 262: end 263: end 264: add_conversion_proc(1082, pr) 265: 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, line 371 371: def copy_into(table, opts=OPTS) 372: data = opts[:data] 373: data = Array(data) if data.is_a?(String) 374: 375: if block_given? && data 376: raise Error, "Cannot provide both a :data option and a block to copy_into" 377: elsif !block_given? && !data 378: raise Error, "Must provide either a :data option or a block to copy_into" 379: end 380: 381: synchronize(opts[:server]) do |conn| 382: conn.execute(copy_into_sql(table, opts)) 383: begin 384: if block_given? 385: while buf = yield 386: conn.put_copy_data(buf) 387: end 388: else 389: data.each{|buff| conn.put_copy_data(buff)} 390: end 391: rescue Exception => e 392: conn.put_copy_end("ruby exception occurred while copying data into PostgreSQL") 393: ensure 394: conn.put_copy_end unless e 395: while res = conn.get_result 396: raise e if e 397: check_database_errors{res.check} 398: end 399: end 400: end 401: 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 syntax Sequel uses for options is only compatible with PostgreSQL 9.0+. |
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, line 327 327: def copy_table(table, opts=OPTS) 328: synchronize(opts[:server]) do |conn| 329: conn.execute(copy_table_sql(table, opts)) 330: begin 331: if block_given? 332: while buf = conn.get_copy_data 333: yield buf 334: end 335: nil 336: else 337: b = String.new 338: b << buf while buf = conn.get_copy_data 339: b 340: end 341: rescue => e 342: raise_error(e, :disconnect=>true) 343: ensure 344: if buf && !e 345: raise DatabaseDisconnectError, "disconnecting as a partial COPY may leave the connection in an unusable state" 346: end 347: end 348: end 349: end
# File lib/sequel/adapters/postgres.rb, line 267 267: def disconnect_connection(conn) 268: conn.finish 269: rescue PGError, IOError 270: nil 271: end
Return a hash of information about the related PGError (or Sequel::DatabaseError that wraps a PGError), with the following entries:
: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 |
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, line 285 285: def error_info(e) 286: e = e.wrapped_exception if e.is_a?(DatabaseError) 287: r = e.result 288: h = {} 289: h[:schema] = r.error_field(::PG::PG_DIAG_SCHEMA_NAME) 290: h[:table] = r.error_field(::PG::PG_DIAG_TABLE_NAME) 291: h[:column] = r.error_field(::PG::PG_DIAG_COLUMN_NAME) 292: h[:constraint] = r.error_field(::PG::PG_DIAG_CONSTRAINT_NAME) 293: h[:type] = r.error_field(::PG::PG_DIAG_DATATYPE_NAME) 294: h 295: end
# File lib/sequel/adapters/postgres.rb, line 298 298: def execute(sql, opts=OPTS, &block) 299: synchronize(opts[:server]){|conn| check_database_errors{_execute(conn, sql, opts, &block)}} 300: 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 to listen, 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:
# File lib/sequel/adapters/postgres.rb, line 426 426: def listen(channels, opts=OPTS, &block) 427: check_database_errors do 428: synchronize(opts[:server]) do |conn| 429: begin 430: channels = Array(channels) 431: channels.each do |channel| 432: sql = "LISTEN ".dup 433: dataset.send(:identifier_append, sql, channel) 434: conn.execute(sql) 435: end 436: opts[:after_listen].call(conn) if opts[:after_listen] 437: timeout = opts[:timeout] 438: if timeout 439: timeout_block = timeout.respond_to?(:call) ? timeout : proc{timeout} 440: end 441: 442: if l = opts[:loop] 443: raise Error, 'calling #listen with :loop requires a block' unless block 444: loop_call = l.respond_to?(:call) 445: catch(:stop) do 446: loop do 447: t = timeout_block ? [timeout_block.call] : [] 448: conn.wait_for_notify(*t, &block) 449: l.call(conn) if loop_call 450: end 451: end 452: nil 453: else 454: t = timeout_block ? [timeout_block.call] : [] 455: conn.wait_for_notify(*t, &block) 456: end 457: ensure 458: conn.execute("UNLISTEN *") 459: end 460: end 461: end 462: end
If convert_infinite_timestamps is true and the value is infinite, return an appropriate value based on the convert_infinite_timestamps setting.
# File lib/sequel/adapters/postgres.rb, line 467 467: def to_application_timestamp(value) 468: if convert_infinite_timestamps 469: case value 470: when *INFINITE_TIMESTAMP_STRINGS 471: infinite_timestamp_value(value) 472: else 473: super 474: end 475: else 476: super 477: end 478: end