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 |
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", and it won‘t ever handle Sequel::SQLTime values correctly. Only public for use by the adapter, shouldn‘t be used by external code.
# File lib/sequel/adapters/postgres.rb, line 185 185: def bound_variable_arg(arg, conn) 186: case arg 187: when Sequel::SQL::Blob 188: conn.escape_bytea(arg) 189: when Sequel::SQLTime 190: literal(arg) 191: when DateTime, Time 192: literal(arg) 193: else 194: arg 195: end 196: 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, and :sslmode sets whether postgres‘s sslmode. :connect_timeout and :ssl_mode are only supported if the pg driver is used.
# File lib/sequel/adapters/postgres.rb, line 204 204: def connect(server) 205: opts = server_opts(server) 206: conn = if SEQUEL_POSTGRES_USES_PG 207: connection_params = { 208: :host => opts[:host], 209: :port => opts[:port] || 5432, 210: :dbname => opts[:database], 211: :user => opts[:user], 212: :password => opts[:password], 213: :connect_timeout => opts[:connect_timeout] || 20, 214: :sslmode => opts[:sslmode] 215: }.delete_if { |key, value| blank_object?(value) } 216: Adapter.connect(connection_params) 217: else 218: Adapter.connect( 219: (opts[:host] unless blank_object?(opts[:host])), 220: opts[:port] || 5432, 221: nil, '', 222: opts[:database], 223: opts[:user], 224: opts[:password] 225: ) 226: end 227: if encoding = opts[:encoding] || opts[:charset] 228: if conn.respond_to?(:set_client_encoding) 229: conn.set_client_encoding(encoding) 230: else 231: conn.async_exec("set client_encoding to '#{encoding}'") 232: end 233: end 234: conn.instance_variable_set(:@db, self) 235: conn.instance_variable_set(:@prepared_statements, {}) if SEQUEL_POSTGRES_USES_PG 236: connection_configuration_sqls.each{|sql| conn.execute(sql)} 237: conn 238: 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 242 242: def convert_infinite_timestamps=(v) 243: @convert_infinite_timestamps = case v 244: when Symbol 245: v 246: when 'nil' 247: :nil 248: when 'string' 249: :string 250: when 'float' 251: :float 252: when String 253: typecast_value_boolean(v) 254: else 255: false 256: end 257: 258: pr = old_pr = @use_iso_date_format ? TYPE_TRANSLATOR.method(:date) : Sequel.method(:string_to_date) 259: if v 260: pr = lambda do |val| 261: case val 262: when *INFINITE_TIMESTAMP_STRINGS 263: infinite_timestamp_value(val) 264: else 265: old_pr.call(val) 266: end 267: end 268: end 269: conversion_procs[1082] = pr 270: 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 375 375: def copy_into(table, opts=OPTS) 376: data = opts[:data] 377: data = Array(data) if data.is_a?(String) 378: 379: if block_given? && data 380: raise Error, "Cannot provide both a :data option and a block to copy_into" 381: elsif !block_given? && !data 382: raise Error, "Must provide either a :data option or a block to copy_into" 383: end 384: 385: synchronize(opts[:server]) do |conn| 386: conn.execute(copy_into_sql(table, opts)) 387: begin 388: if block_given? 389: while buf = yield 390: conn.put_copy_data(buf) 391: end 392: else 393: data.each{|buff| conn.put_copy_data(buff)} 394: end 395: rescue Exception => e 396: conn.put_copy_end("ruby exception occurred while copying data into PostgreSQL") 397: ensure 398: conn.put_copy_end unless e 399: while res = conn.get_result 400: raise e if e 401: check_database_errors{res.check} 402: end 403: end 404: end 405: 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 335 335: def copy_table(table, opts=OPTS) 336: synchronize(opts[:server]) do |conn| 337: conn.execute(copy_table_sql(table, opts)) 338: begin 339: if block_given? 340: while buf = conn.get_copy_data 341: yield buf 342: end 343: nil 344: else 345: b = '' 346: b << buf while buf = conn.get_copy_data 347: b 348: end 349: ensure 350: raise DatabaseDisconnectError, "disconnecting as a partial COPY may leave the connection in an unusable state" if buf 351: end 352: end 353: end
Disconnect given connection
# File lib/sequel/adapters/postgres.rb, line 273 273: def disconnect_connection(conn) 274: begin 275: conn.finish 276: rescue PGError, IOError 277: end 278: 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 292 292: def error_info(e) 293: e = e.wrapped_exception if e.is_a?(DatabaseError) 294: r = e.result 295: h = {} 296: h[:schema] = r.error_field(::PG::PG_DIAG_SCHEMA_NAME) 297: h[:table] = r.error_field(::PG::PG_DIAG_TABLE_NAME) 298: h[:column] = r.error_field(::PG::PG_DIAG_COLUMN_NAME) 299: h[:constraint] = r.error_field(::PG::PG_DIAG_CONSTRAINT_NAME) 300: h[:type] = r.error_field(::PG::PG_DIAG_DATATYPE_NAME) 301: h 302: 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 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 428 428: def listen(channels, opts=OPTS, &block) 429: check_database_errors do 430: synchronize(opts[:server]) do |conn| 431: begin 432: channels = Array(channels) 433: channels.each do |channel| 434: sql = "LISTEN " 435: dataset.send(:identifier_append, sql, channel) 436: conn.execute(sql) 437: end 438: opts[:after_listen].call(conn) if opts[:after_listen] 439: timeout = opts[:timeout] ? [opts[:timeout]] : [] 440: if l = opts[:loop] 441: raise Error, 'calling #listen with :loop requires a block' unless block 442: loop_call = l.respond_to?(:call) 443: catch(:stop) do 444: loop do 445: conn.wait_for_notify(*timeout, &block) 446: l.call(conn) if loop_call 447: end 448: end 449: nil 450: else 451: conn.wait_for_notify(*timeout, &block) 452: end 453: ensure 454: conn.execute("UNLISTEN *") 455: end 456: end 457: end 458: 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 463 463: def to_application_timestamp(value) 464: if convert_infinite_timestamps 465: case value 466: when *INFINITE_TIMESTAMP_STRINGS 467: infinite_timestamp_value(value) 468: else 469: super 470: end 471: else 472: super 473: end 474: end