Class: Sequel::Postgres::Database
- Includes:
- DatabaseMethods
- Defined in:
- lib/sequel/adapters/postgres.rb
Overview
Database class for PostgreSQL databases used with Sequel and the pg, postgres, or postgres-pr driver.
Constant Summary collapse
- DatasetClass =
self
Constants included from DatabaseMethods
Sequel::Postgres::DatabaseMethods::EXCLUDE_SCHEMAS, Sequel::Postgres::DatabaseMethods::PREPARED_ARG_PLACEHOLDER, Sequel::Postgres::DatabaseMethods::RE_CURRVAL_ERROR, Sequel::Postgres::DatabaseMethods::SYSTEM_TABLE_REGEXP
Constants inherited from Database
Database::ADAPTERS, Database::AUTOINCREMENT, Database::CASCADE, Database::COLUMN_DEFINITION_ORDER, Database::COMMA_SEPARATOR, Database::MSSQL_DEFAULT_RE, Database::MYSQL_TIMESTAMP_RE, Database::NOT_NULL, Database::NO_ACTION, Database::NULL, Database::POSTGRES_DEFAULT_RE, Database::PRIMARY_KEY, Database::RESTRICT, Database::SET_DEFAULT, Database::SET_NULL, Database::SQL_BEGIN, Database::SQL_COMMIT, Database::SQL_RELEASE_SAVEPOINT, Database::SQL_ROLLBACK, Database::SQL_ROLLBACK_TO_SAVEPOINT, Database::SQL_SAVEPOINT, Database::STRING_DEFAULT_RE, Database::TEMPORARY, Database::TRANSACTION_BEGIN, Database::TRANSACTION_COMMIT, Database::TRANSACTION_ISOLATION_LEVELS, Database::TRANSACTION_ROLLBACK, Database::UNDERSCORE, Database::UNIQUE, Database::UNSIGNED
Instance Attribute Summary collapse
-
#conversion_procs ⇒ Object
readonly
A hash of conversion procs, keyed by type integer (oid) and having callable values for the conversion proc for that type.
Attributes inherited from Database
#dataset_class, #default_schema, #log_warn_duration, #loggers, #opts, #pool, #prepared_statements, #sql_log_level, #timezone, #transaction_isolation_level
Instance Method Summary collapse
-
#connect(server) ⇒ Object
Connects to the database.
-
#copy_table(table, opts = {}) ⇒ Object
copy_table
uses PostgreSQL’sCOPY
SQL statement to return formatted results directly to the caller. -
#execute(sql, opts = {}, &block) ⇒ Object
Execute the given SQL with the given args on an available connection.
-
#execute_insert(sql, opts = {}) ⇒ Object
Insert the values into the table and return the primary key (if automatically generated).
-
#initialize(*args) ⇒ Database
constructor
Add the primary_keys and primary_key_sequences instance variables, so we can get the correct return values for inserted rows.
-
#listen(channels, opts = {}, &block) ⇒ Object
Listens on the given channel (or multiple channels if channel is an array), waiting for notifications.
Methods included from DatabaseMethods
#commit_prepared_transaction, #create_function, #create_language, #create_trigger, #database_type, #drop_function, #drop_language, #drop_trigger, #indexes, #locks, #notify, #primary_key, #primary_key_sequence, #reset_primary_key_sequence, #rollback_prepared_transaction, #serial_primary_key_options, #server_version, #supports_create_table_if_not_exists?, #supports_prepared_transactions?, #supports_savepoints?, #supports_transaction_isolation_levels?, #tables, #views
Methods inherited from Database
#<<, #[], adapter_class, #adapter_scheme, adapter_scheme, #add_column, #add_index, #add_servers, #after_commit, #after_rollback, #alter_table, #call, #cast_type_literal, connect, #create_or_replace_view, #create_table, #create_table!, #create_table?, #create_view, #database_type, #dataset, #disconnect, #drop_column, #drop_index, #drop_table, #drop_view, #dump_indexes_migration, #dump_schema_migration, #dump_table_schema, #each_server, #execute_ddl, #execute_dui, #extend_datasets, #fetch, #from, #from_application_timestamp, #get, #identifier_input_method, identifier_input_method, identifier_input_method=, #identifier_input_method=, #identifier_output_method, identifier_output_method, identifier_output_method=, #identifier_output_method=, #in_transaction?, #indexes, #inspect, #literal, #log_info, #log_yield, #logger=, #query, #quote_identifiers=, quote_identifiers=, #quote_identifiers?, #remove_servers, #rename_column, #rename_table, #run, #schema, #select, #serial_primary_key_options, #servers, #set_column_default, #set_column_type, single_threaded=, #single_threaded?, #supports_create_table_if_not_exists?, #supports_prepared_transactions?, #supports_savepoints?, #supports_transaction_isolation_levels?, #synchronize, #table_exists?, #tables, #test_connection, #to_application_timestamp, #transaction, #typecast_value, #uri, #url, #views
Methods included from Metaprogramming
Constructor Details
#initialize(*args) ⇒ Database
Add the primary_keys and primary_key_sequences instance variables, so we can get the correct return values for inserted rows.
210 211 212 213 214 |
# File 'lib/sequel/adapters/postgres.rb', line 210 def initialize(*args) super @primary_keys = {} @primary_key_sequences = {} end |
Instance Attribute Details
#conversion_procs ⇒ Object (readonly)
A hash of conversion procs, keyed by type integer (oid) and having callable values for the conversion proc for that type.
206 207 208 |
# File 'lib/sequel/adapters/postgres.rb', line 206 def conversion_procs @conversion_procs end |
Instance Method Details
#connect(server) ⇒ Object
Connects to the database. In addition to the standard database options, using the :encoding or :charset option changes the client encoding for the connection.
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
# File 'lib/sequel/adapters/postgres.rb', line 219 def connect(server) opts = server_opts(server) conn = if SEQUEL_POSTGRES_USES_PG connection_params = { :host => opts[:host], :port => opts[:port] || 5432, :tty => '', :dbname => opts[:database], :user => opts[:user], :password => opts[:password], :connect_timeout => opts[:connect_timeout] || 20 }.delete_if { |key, value| blank_object?(value) } Adapter.connect(connection_params) else Adapter.connect( (opts[:host] unless blank_object?(opts[:host])), opts[:port] || 5432, nil, '', opts[:database], opts[:user], opts[:password] ) end if encoding = opts[:encoding] || opts[:charset] if conn.respond_to?(:set_client_encoding) conn.set_client_encoding(encoding) else conn.async_exec("set client_encoding to '#{encoding}'") end end conn.db = self conn.apply_connection_settings @conversion_procs ||= get_conversion_procs(conn) conn end |
#copy_table(table, opts = {}) ⇒ Object
copy_table
uses PostgreSQL’s COPY
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 FROM or COPY TO with a filename, you should just use run
instead of this method. This method does not currently support COPY FROM STDIN, but that may be supported in the future.
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.
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 |
# File 'lib/sequel/adapters/postgres.rb', line 302 def copy_table(table, opts={}) sql = if table.is_a?(String) sql = table else if opts[:options] || opts[:format] = " (" << "FORMAT #{opts[:format]}" if opts[:format] << "#{', ' if opts[:format]}#{opts[:options]}" if opts[:options] << ')' end table = if table.is_a?(::Sequel::Dataset) "(#{table.sql})" else literal(table) end sql = "COPY #{table} TO STDOUT#{}" end synchronize(opts[:server]) do |conn| conn.execute(sql) begin if block_given? while buf = conn.get_copy_data yield buf end nil else b = '' b << buf while buf = conn.get_copy_data b end ensure raise DatabaseDisconnectError, "disconnecting as a partial COPY may leave the connection in an unusable state" if buf end end end |
#execute(sql, opts = {}, &block) ⇒ Object
Execute the given SQL with the given args on an available connection.
256 257 258 259 260 261 |
# File 'lib/sequel/adapters/postgres.rb', line 256 def execute(sql, opts={}, &block) check_database_errors do return execute_prepared_statement(sql, opts, &block) if Symbol === sql synchronize(opts[:server]){|conn| conn.execute(sql, opts[:arguments], &block)} end end |
#execute_insert(sql, opts = {}) ⇒ Object
Insert the values into the table and return the primary key (if automatically generated).
265 266 267 268 269 270 271 272 273 |
# File 'lib/sequel/adapters/postgres.rb', line 265 def execute_insert(sql, opts={}) return execute(sql, opts) if Symbol === sql check_database_errors do synchronize(opts[:server]) do |conn| conn.execute(sql, opts[:arguments]) insert_result(conn, opts[:table], opts[:values]) end end end |
#listen(channels, opts = {}, &block) ⇒ Object
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:
-
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).
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 |
# File 'lib/sequel/adapters/postgres.rb', line 359 def listen(channels, opts={}, &block) check_database_errors do synchronize(opts[:server]) do |conn| begin channels = Array(channels) channels.each{|channel| conn.execute("LISTEN #{channel}")} opts[:after_listen].call(conn) if opts[:after_listen] timeout = opts[:timeout] ? [opts[:timeout]] : [] if l = opts[:loop] raise Error, 'calling #listen with :loop requires a block' unless block loop_call = l.respond_to?(:call) catch(:stop) do loop do conn.wait_for_notify(*timeout, &block) l.call(conn) if loop_call end end nil else conn.wait_for_notify(*timeout, &block) end ensure conn.execute("UNLISTEN *") end end end end |