Class Index [+]

Quicksearch

Sequel::Postgres::DatabaseMethods

Methods shared by Database instances that connect to PostgreSQL.

Constants

EXCLUDE_SCHEMAS
PREPARED_ARG_PLACEHOLDER
RE_CURRVAL_ERROR
SYSTEM_TABLE_REGEXP
FOREIGN_KEY_LIST_ON_DELETE_MAP
SELECT_CUSTOM_SEQUENCE_SQL

SQL fragment for custom sequences (ones not created by serial primary key), Returning the schema and literal form of the sequence name, by parsing the column defaults table.

SELECT_PK_SQL

SQL fragment for determining primary key column for the given table. Only returns the first primary key if the table has a composite primary key.

SELECT_SERIAL_SEQUENCE_SQL

SQL fragment for getting sequence associated with table’s primary key, assuming it was a serial primary key column.

Public Instance Methods

commit_prepared_transaction(transaction_id) click to toggle source

Commit an existing prepared transaction with the given transaction identifier string.

     # File lib/sequel/adapters/shared/postgres.rb, line 114
114:       def commit_prepared_transaction(transaction_id)
115:         run("COMMIT PREPARED #{literal(transaction_id)}")
116:       end
create_function(name, definition, opts={}) click to toggle source

Creates the function in the database. Arguments:

  • name : name of the function to create

  • definition : string definition of the function, or object file for a dynamically loaded C function.

  • opts : options hash:

    • :args : function arguments, can be either a symbol or string specifying a type or an array of 1-3 elements:

      • element 1 : argument data type

      • element 2 : argument name

      • element 3 : argument mode (e.g. in, out, inout)

    • :behavior : Should be IMMUTABLE, STABLE, or VOLATILE. PostgreSQL assumes VOLATILE by default.

    • :cost : The estimated cost of the function, used by the query planner.

    • :language : The language the function uses. SQL is the default.

    • :link_symbol : For a dynamically loaded see function, the function’s link symbol if different from the definition argument.

    • :returns : The data type returned by the function. If you are using OUT or INOUT argument modes, this is ignored. Otherwise, if this is not specified, void is used by default to specify the function is not supposed to return a value.

    • :rows : The estimated number of rows the function will return. Only use if the function returns SETOF something.

    • :security_definer : Makes the privileges of the function the same as the privileges of the user who defined the function instead of the privileges of the user who runs the function. There are security implications when doing this, see the PostgreSQL documentation.

    • :set : Configuration variables to set while the function is being run, can be a hash or an array of two pairs. search_path is often used here if :security_definer is used.

    • :strict : Makes the function return NULL when any argument is NULL.

     # File lib/sequel/adapters/shared/postgres.rb, line 138
138:       def create_function(name, definition, opts={})
139:         self << create_function_sql(name, definition, opts)
140:       end
create_language(name, opts={}) click to toggle source

Create the procedural language in the database. Arguments:

  • name : Name of the procedural language (e.g. plpgsql)

  • opts : options hash:

    • :handler : The name of a previously registered function used as a call handler for this language.

    • :replace: Replace the installed language if it already exists (on PostgreSQL 9.0+).

    • :trusted : Marks the language being created as trusted, allowing unprivileged users to create functions using this language.

    • :validator : The name of previously registered function used as a validator of functions defined in this language.

     # File lib/sequel/adapters/shared/postgres.rb, line 149
149:       def create_language(name, opts={})
150:         self << create_language_sql(name, opts)
151:       end
create_schema(name) click to toggle source

Create a schema in the database. Arguments:

  • name : Name of the schema (e.g. admin)

     # File lib/sequel/adapters/shared/postgres.rb, line 155
155:       def create_schema(name)
156:         self << create_schema_sql(name)
157:       end
create_trigger(table, name, function, opts={}) click to toggle source

Create a trigger in the database. Arguments:

  • table : the table on which this trigger operates

  • name : the name of this trigger

  • function : the function to call for this trigger, which should return type trigger.

  • opts : options hash:

    • :after : Calls the trigger after execution instead of before.

    • :args : An argument or array of arguments to pass to the function.

    • :each_row : Calls the trigger for each row instead of for each statement.

    • :events : Can be :insert, :update, :delete, or an array of any of those. Calls the trigger whenever that type of statement is used. By default, the trigger is called for insert, update, or delete.

     # File lib/sequel/adapters/shared/postgres.rb, line 169
169:       def create_trigger(table, name, function, opts={})
170:         self << create_trigger_sql(table, name, function, opts)
171:       end
database_type() click to toggle source

PostgreSQL uses the :postgres database type.

     # File lib/sequel/adapters/shared/postgres.rb, line 174
174:       def database_type
175:         :postgres
176:       end
drop_function(name, opts={}) click to toggle source

Drops the function from the database. Arguments:

  • name : name of the function to drop

  • opts : options hash:

    • :args : The arguments for the function. See create_function_sql.

    • :cascade : Drop other objects depending on this function.

    • :if_exists : Don’t raise an error if the function doesn’t exist.

     # File lib/sequel/adapters/shared/postgres.rb, line 184
184:       def drop_function(name, opts={})
185:         self << drop_function_sql(name, opts)
186:       end
drop_language(name, opts={}) click to toggle source

Drops a procedural language from the database. Arguments:

  • name : name of the procedural language to drop

  • opts : options hash:

    • :cascade : Drop other objects depending on this function.

    • :if_exists : Don’t raise an error if the function doesn’t exist.

     # File lib/sequel/adapters/shared/postgres.rb, line 193
193:       def drop_language(name, opts={})
194:         self << drop_language_sql(name, opts)
195:       end
drop_schema(name, opts={}) click to toggle source

Drops a schema from the database. Arguments:

  • name : name of the schema to drop

  • opts : options hash:

    • :cascade : Drop all objects in this schema.

    • :if_exists : Don’t raise an error if the schema doesn’t exist.

     # File lib/sequel/adapters/shared/postgres.rb, line 202
202:       def drop_schema(name, opts={})
203:         self << drop_schema_sql(name, opts)
204:       end
drop_trigger(table, name, opts={}) click to toggle source

Drops a trigger from the database. Arguments:

  • table : table from which to drop the trigger

  • name : name of the trigger to drop

  • opts : options hash:

    • :cascade : Drop other objects depending on this function.

    • :if_exists : Don’t raise an error if the function doesn’t exist.

     # File lib/sequel/adapters/shared/postgres.rb, line 212
212:       def drop_trigger(table, name, opts={})
213:         self << drop_trigger_sql(table, name, opts)
214:       end
foreign_key_list(table, opts={}) click to toggle source

Return full foreign key information using the pg system tables, including :name, :on_delete, :on_update, and :deferrable entries in the hashes.

     # File lib/sequel/adapters/shared/postgres.rb, line 218
218:       def foreign_key_list(table, opts={})
219:         m = output_identifier_meth
220:         im = input_identifier_meth
221:         schema, table = schema_and_table(table)
222:         range = 0...32
223: 
224:         base_ds = metadata_dataset.
225:           where(:cl__relkind=>'r', :co__contype=>'f', :cl__relname=>im.call(table)).
226:           from(:pg_constraint___co).
227:           join(:pg_class___cl, :oid=>:conrelid)
228: 
229:         # We split the parsing into two separate queries, which are merged manually later.
230:         # This is because PostgreSQL stores both the referencing and referenced columns in
231:         # arrays, and I don't know a simple way to not create a cross product, as PostgreSQL
232:         # doesn't appear to have a function that takes an array and element and gives you
233:         # the index of that element in the array.
234: 
235:         ds = base_ds.
236:           join(:pg_attribute___att, :attrelid=>:oid, :attnum=>SQL::Function.new(:ANY, :co__conkey)).
237:           order(:co__conname, SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(:co__conkey, [x]), x]}, 32, :att__attnum)).
238:           select(:co__conname___name, :att__attname___column, :co__confupdtype___on_update, :co__confdeltype___on_delete,
239:                  SQL::BooleanExpression.new(:AND, :co__condeferrable, :co__condeferred).as(:deferrable))
240: 
241:         ref_ds = base_ds.
242:           join(:pg_class___cl2, :oid=>:co__confrelid).
243:           join(:pg_attribute___att2, :attrelid=>:oid, :attnum=>SQL::Function.new(:ANY, :co__confkey)).
244:           order(:co__conname, SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(:co__conkey, [x]), x]}, 32, :att2__attnum)).
245:           select(:co__conname___name, :cl2__relname___table, :att2__attname___refcolumn)
246: 
247:         # If a schema is given, we only search in that schema, and the returned :table
248:         # entry is schema qualified as well.
249:         if schema
250:           ds = ds.join(:pg_namespace___nsp, :oid=>:cl__relnamespace).
251:             where(:nsp__nspname=>im.call(schema))
252:           ref_ds = ref_ds.join(:pg_namespace___nsp2, :oid=>:cl2__relnamespace).
253:             select_more(:nsp2__nspname___schema)
254:         end
255: 
256:         h = {}
257:         fklod_map = FOREIGN_KEY_LIST_ON_DELETE_MAP 
258:         ds.each do |row|
259:           if r = h[row[:name]]
260:             r[:columns] << m.call(row[:column])
261:           else
262:             h[row[:name]] = {:name=>m.call(row[:name]), :columns=>[m.call(row[:column])], :on_update=>fklod_map[row[:on_update]], :on_delete=>fklod_map[row[:on_delete]], :deferrable=>row[:deferrable]}
263:           end
264:         end
265:         ref_ds.each do |row|
266:           r = h[row[:name]]
267:           r[:table] ||= schema ? SQL::QualifiedIdentifier.new(m.call(row[:schema]), m.call(row[:table])) : m.call(row[:table])
268:           r[:key] ||= []
269:           r[:key] << m.call(row[:refcolumn])
270:         end
271:         h.values
272:       end
indexes(table, opts={}) click to toggle source

Use the pg_* system tables to determine indexes on a table

     # File lib/sequel/adapters/shared/postgres.rb, line 275
275:       def indexes(table, opts={})
276:         m = output_identifier_meth
277:         im = input_identifier_meth
278:         schema, table = schema_and_table(table)
279:         range = 0...32
280:         attnums = server_version >= 80100 ? SQL::Function.new(:ANY, :ind__indkey) : range.map{|x| SQL::Subscript.new(:ind__indkey, [x])}
281:         ds = metadata_dataset.
282:           from(:pg_class___tab).
283:           join(:pg_index___ind, :indrelid=>:oid, im.call(table)=>:relname).
284:           join(:pg_class___indc, :oid=>:indexrelid).
285:           join(:pg_attribute___att, :attrelid=>:tab__oid, :attnum=>attnums).
286:           filter(:indc__relkind=>'i', :ind__indisprimary=>false, :indexprs=>nil, :indpred=>nil, :indisvalid=>true).
287:           order(:indc__relname, SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(:ind__indkey, [x]), x]}, 32, :att__attnum)).
288:           select(:indc__relname___name, :ind__indisunique___unique, :att__attname___column)
289: 
290:         ds.join!(:pg_namespace___nsp, :oid=>:tab__relnamespace, :nspname=>schema.to_s) if schema
291:         ds.filter!(:indisready=>true, :indcheckxmin=>false) if server_version >= 80300
292: 
293:         indexes = {}
294:         ds.each do |r|
295:           i = indexes[m.call(r[:name])] ||= {:columns=>[], :unique=>r[:unique]}
296:           i[:columns] << m.call(r[:column])
297:         end
298:         indexes
299:       end
locks() click to toggle source

Dataset containing all current database locks

     # File lib/sequel/adapters/shared/postgres.rb, line 302
302:       def locks
303:         dataset.from(:pg_class).join(:pg_locks, :relation=>:relfilenode).select(:pg_class__relname, Sequel::SQL::ColumnAll.new(:pg_locks))
304:       end
notify(channel, opts={}) click to toggle source

Notifies the given channel. See the PostgreSQL NOTIFY documentation. Options:

:payload

The payload string to use for the NOTIFY statement. Only supported in PostgreSQL 9.0+.

:server

The server to which to send the NOTIFY statement, if the sharding support is being used.

     # File lib/sequel/adapters/shared/postgres.rb, line 312
312:       def notify(channel, opts={})
313:         execute_ddl("NOTIFY #{channel}#{", #{literal(opts[:payload].to_s)}" if opts[:payload]}", opts)
314:       end
primary_key(table, opts={}) click to toggle source

Return primary key for the given table.

     # File lib/sequel/adapters/shared/postgres.rb, line 317
317:       def primary_key(table, opts={})
318:         quoted_table = quote_schema_table(table)
319:         @primary_keys.fetch(quoted_table) do
320:           schema, table = schema_and_table(table)
321:           sql = "#{SELECT_PK_SQL} AND pg_class.relname = #{literal(table)}"
322:           sql << "AND pg_namespace.nspname = #{literal(schema)}" if schema
323:           @primary_keys[quoted_table] = fetch(sql).single_value
324:         end
325:       end
primary_key_sequence(table, opts={}) click to toggle source

Return the sequence providing the default for the primary key for the given table.

     # File lib/sequel/adapters/shared/postgres.rb, line 328
328:       def primary_key_sequence(table, opts={})
329:         quoted_table = quote_schema_table(table)
330:         @primary_key_sequences.fetch(quoted_table) do
331:           schema, table = schema_and_table(table)
332:           table = literal(table)
333:           sql = "#{SELECT_SERIAL_SEQUENCE_SQL} AND seq.relname = #{table}"
334:           sql << " AND name.nspname = #{literal(schema)}" if schema
335:           unless pks = fetch(sql).single_record
336:             sql = "#{SELECT_CUSTOM_SEQUENCE_SQL} AND t.relname = #{table}"
337:             sql << " AND name.nspname = #{literal(schema)}" if schema
338:             pks = fetch(sql).single_record
339:           end
340: 
341:           @primary_key_sequences[quoted_table] = if pks
342:             literal(SQL::QualifiedIdentifier.new(pks[:schema], LiteralString.new(pks[:sequence])))
343:           end
344:         end
345:       end
reset_primary_key_sequence(table) click to toggle source

Reset the primary key sequence for the given table, baseing it on the maximum current value of the table’s primary key.

     # File lib/sequel/adapters/shared/postgres.rb, line 349
349:       def reset_primary_key_sequence(table)
350:         return unless seq = primary_key_sequence(table)
351:         pk = SQL::Identifier.new(primary_key(table))
352:         db = self
353:         seq_ds = db.from(LiteralString.new(seq))
354:         get{setval(seq, db[table].select{coalesce(max(pk)+seq_ds.select{:increment_by}, seq_ds.select(:min_value))}, false)}
355:       end
rollback_prepared_transaction(transaction_id) click to toggle source

Rollback an existing prepared transaction with the given transaction identifier string.

     # File lib/sequel/adapters/shared/postgres.rb, line 359
359:       def rollback_prepared_transaction(transaction_id)
360:         run("ROLLBACK PREPARED #{literal(transaction_id)}")
361:       end
serial_primary_key_options() click to toggle source

PostgreSQL uses SERIAL psuedo-type instead of AUTOINCREMENT for managing incrementing primary keys.

     # File lib/sequel/adapters/shared/postgres.rb, line 365
365:       def serial_primary_key_options
366:         {:primary_key => true, :serial => true, :type=>Integer}
367:       end
server_version(server=nil) click to toggle source

The version of the PostgreSQL server, used for determining capability.

     # File lib/sequel/adapters/shared/postgres.rb, line 370
370:       def server_version(server=nil)
371:         return @server_version if @server_version
372:         @server_version = synchronize(server) do |conn|
373:           (conn.server_version rescue nil) if conn.respond_to?(:server_version)
374:         end
375:         unless @server_version
376:           @server_version = if m = /PostgreSQL (\d+)\.(\d+)(?:(?:rc\d+)|\.(\d+))?/.match(fetch('SELECT version()').single_value)
377:             (m[1].to_i * 10000) + (m[2].to_i * 100) + m[3].to_i
378:           else
379:             0
380:           end
381:         end
382:         warn 'Sequel no longer supports PostgreSQL <8.2, some things may not work' if @server_version < 80200
383:         @server_version
384:       end
supports_create_table_if_not_exists?() click to toggle source

PostgreSQL supports CREATE TABLE IF NOT EXISTS on 9.1+

     # File lib/sequel/adapters/shared/postgres.rb, line 387
387:       def supports_create_table_if_not_exists?
388:         server_version >= 90100
389:       end
supports_drop_table_if_exists?() click to toggle source

PostgreSQL supports DROP TABLE IF EXISTS

     # File lib/sequel/adapters/shared/postgres.rb, line 392
392:       def supports_drop_table_if_exists?
393:         true
394:       end
supports_prepared_transactions?() click to toggle source

PostgreSQL supports prepared transactions (two-phase commit) if max_prepared_transactions is greater than 0.

     # File lib/sequel/adapters/shared/postgres.rb, line 398
398:       def supports_prepared_transactions?
399:         return @supports_prepared_transactions if defined?(@supports_prepared_transactions)
400:         @supports_prepared_transactions = self['SHOW max_prepared_transactions'].get.to_i > 0
401:       end
supports_savepoints?() click to toggle source

PostgreSQL supports savepoints

     # File lib/sequel/adapters/shared/postgres.rb, line 404
404:       def supports_savepoints?
405:         true
406:       end
supports_transaction_isolation_levels?() click to toggle source

PostgreSQL supports transaction isolation levels

     # File lib/sequel/adapters/shared/postgres.rb, line 409
409:       def supports_transaction_isolation_levels?
410:         true
411:       end
supports_transactional_ddl?() click to toggle source

PostgreSQL supports transaction DDL statements.

     # File lib/sequel/adapters/shared/postgres.rb, line 414
414:       def supports_transactional_ddl?
415:         true
416:       end
tables(opts={}, &block) click to toggle source

Array of symbols specifying table names in the current database. The dataset used is yielded to the block if one is provided, otherwise, an array of symbols of table names is returned.

Options:

  • :schema - The schema to search (default_schema by default)

  • :server - The server to use

     # File lib/sequel/adapters/shared/postgres.rb, line 425
425:       def tables(opts={}, &block)
426:         pg_class_relname('r', opts, &block)
427:       end
type_supported?(type) click to toggle source

Check whether the given type name string/symbol (e.g. :hstore) is supported by the database.

     # File lib/sequel/adapters/shared/postgres.rb, line 431
431:       def type_supported?(type)
432:         @supported_types ||= {}
433:         @supported_types.fetch(type){@supported_types[type] = (from(:pg_type).filter(:typtype=>'b', :typname=>type.to_s).count > 0)}
434:       end
views(opts={}) click to toggle source

Array of symbols specifying view names in the current database.

Options:

  • :schema - The schema to search (default_schema by default)

  • :server - The server to use

     # File lib/sequel/adapters/shared/postgres.rb, line 441
441:       def views(opts={})
442:         pg_class_relname('v', opts)
443:       end

Private Instance Methods

alter_table_sql(table, op) click to toggle source

Handle :using option for set_column_type op.

     # File lib/sequel/adapters/shared/postgres.rb, line 448
448:       def alter_table_sql(table, op)
449:         case op[:op]
450:         when :set_column_type
451:           s = super
452:           if using = op[:using]
453:             using = Sequel::LiteralString.new(using) if using.is_a?(String)
454:             s << ' USING '
455:             s << literal(using)
456:           end
457:           s
458:         else
459:           super
460:         end
461:       end
begin_new_transaction(conn, opts) click to toggle source

If the :synchronous option is given and non-nil, set synchronous_commit appropriately. Valid values for the :synchronous option are true, :on, false, :off, :local, and :remote_write.

     # File lib/sequel/adapters/shared/postgres.rb, line 466
466:       def begin_new_transaction(conn, opts)
467:         super
468:         if opts.has_key?(:synchronous)
469:           case sync = opts[:synchronous]
470:           when true
471:             sync = :on
472:           when false
473:             sync = :off
474:           when nil
475:             return
476:           end
477: 
478:           log_connection_execute(conn, "SET LOCAL synchronous_commit = #{sync}")
479:         end
480:       end
commit_transaction(conn, opts={}) click to toggle source

If the :prepare option is given and we aren’t in a savepoint, prepare the transaction for a two-phase commit.

     # File lib/sequel/adapters/shared/postgres.rb, line 484
484:       def commit_transaction(conn, opts={})
485:         if (s = opts[:prepare]) && _trans(conn)[:savepoint_level] <= 1
486:           log_connection_execute(conn, "PREPARE TRANSACTION #{literal(s)}")
487:         else
488:           super
489:         end
490:       end
connection_configuration_sqls() click to toggle source

The SQL queries to execute when starting a new connection.

     # File lib/sequel/adapters/shared/postgres.rb, line 493
493:       def connection_configuration_sqls
494:         sqls = []
495:         sqls << "SET standard_conforming_strings = ON" if Postgres.force_standard_strings
496:         if cmm = Postgres.client_min_messages
497:           sqls << "SET client_min_messages = '#{cmm.to_s.upcase}'"
498:         end
499:         sqls
500:       end
create_function_sql(name, definition, opts={}) click to toggle source

SQL statement to create database function.

     # File lib/sequel/adapters/shared/postgres.rb, line 503
503:       def create_function_sql(name, definition, opts={})
504:         args = opts[:args]
505:         if !opts[:args].is_a?(Array) || !opts[:args].any?{|a| Array(a).length == 3 and %OUT INOUT'.include?(a[2].to_s)}
506:           returns = opts[:returns] || 'void'
507:         end
508:         language = opts[:language] || 'SQL'
509:                 CREATE#{' OR REPLACE' if opts[:replace]} FUNCTION #{name}#{sql_function_args(args)}        #{"RETURNS #{returns}" if returns}        LANGUAGE #{language}        #{opts[:behavior].to_s.upcase if opts[:behavior]}        #{'STRICT' if opts[:strict]}        #{'SECURITY DEFINER' if opts[:security_definer]}        #{"COST #{opts[:cost]}" if opts[:cost]}        #{"ROWS #{opts[:rows]}" if opts[:rows]}        #{opts[:set].map{|k,v| " SET #{k} = #{v}"}.join("\n") if opts[:set]}        AS #{literal(definition.to_s)}#{", #{literal(opts[:link_symbol].to_s)}" if opts[:link_symbol]}
510:       end
create_language_sql(name, opts={}) click to toggle source

SQL for creating a procedural language.

     # File lib/sequel/adapters/shared/postgres.rb, line 524
524:       def create_language_sql(name, opts={})
525:         "CREATE#{' OR REPLACE' if opts[:replace] && server_version >= 90000}#{' TRUSTED' if opts[:trusted]} LANGUAGE #{name}#{" HANDLER #{opts[:handler]}" if opts[:handler]}#{" VALIDATOR #{opts[:validator]}" if opts[:validator]}"
526:       end
create_schema_sql(name) click to toggle source

SQL for creating a schema.

     # File lib/sequel/adapters/shared/postgres.rb, line 529
529:       def create_schema_sql(name)
530:         "CREATE SCHEMA #{quote_identifier(name)}"
531:       end
create_trigger_sql(table, name, function, opts={}) click to toggle source

SQL for creating a database trigger.

     # File lib/sequel/adapters/shared/postgres.rb, line 534
534:       def create_trigger_sql(table, name, function, opts={})
535:         events = opts[:events] ? Array(opts[:events]) : [:insert, :update, :delete]
536:         whence = opts[:after] ? 'AFTER' : 'BEFORE'
537:         "CREATE TRIGGER #{name} #{whence} #{events.map{|e| e.to_s.upcase}.join(' OR ')} ON #{quote_schema_table(table)}#{' FOR EACH ROW' if opts[:each_row]} EXECUTE PROCEDURE #{function}(#{Array(opts[:args]).map{|a| literal(a)}.join(', ')})"
538:       end
database_error_classes() click to toggle source

The errors that the main adapters can raise, depends on the adapter being used

     # File lib/sequel/adapters/shared/postgres.rb, line 541
541:       def database_error_classes
542:         CONVERTED_EXCEPTIONS
543:       end
drop_function_sql(name, opts={}) click to toggle source

SQL for dropping a function from the database.

     # File lib/sequel/adapters/shared/postgres.rb, line 546
546:       def drop_function_sql(name, opts={})
547:         "DROP FUNCTION#{' IF EXISTS' if opts[:if_exists]} #{name}#{sql_function_args(opts[:args])}#{' CASCADE' if opts[:cascade]}"
548:       end
drop_index_sql(table, op) click to toggle source

Support :if_exists, :cascade, and :concurrently options.

     # File lib/sequel/adapters/shared/postgres.rb, line 551
551:       def drop_index_sql(table, op)
552:         "DROP INDEX#{' CONCURRENTLY' if op[:concurrently]}#{' IF EXISTS' if op[:if_exists]} #{quote_identifier(op[:name] || default_index_name(table, op[:columns]))}#{' CASCADE' if op[:cascade]}"
553:       end
drop_language_sql(name, opts={}) click to toggle source

SQL for dropping a procedural language from the database.

     # File lib/sequel/adapters/shared/postgres.rb, line 556
556:       def drop_language_sql(name, opts={})
557:         "DROP LANGUAGE#{' IF EXISTS' if opts[:if_exists]} #{name}#{' CASCADE' if opts[:cascade]}"
558:       end
drop_schema_sql(name, opts={}) click to toggle source

SQL for dropping a schema from the database.

     # File lib/sequel/adapters/shared/postgres.rb, line 561
561:       def drop_schema_sql(name, opts={})
562:         "DROP SCHEMA#{' IF EXISTS' if opts[:if_exists]} #{quote_identifier(name)}#{' CASCADE' if opts[:cascade]}"
563:       end
drop_trigger_sql(table, name, opts={}) click to toggle source

SQL for dropping a trigger from the database.

     # File lib/sequel/adapters/shared/postgres.rb, line 566
566:       def drop_trigger_sql(table, name, opts={})
567:         "DROP TRIGGER#{' IF EXISTS' if opts[:if_exists]} #{name} ON #{quote_schema_table(table)}#{' CASCADE' if opts[:cascade]}"
568:       end
filter_schema(ds, opts) click to toggle source

If opts includes a :schema option, or a default schema is used, restrict the dataset to that schema. Otherwise, just exclude the default PostgreSQL schemas except for public.

     # File lib/sequel/adapters/shared/postgres.rb, line 572
572:       def filter_schema(ds, opts)
573:         if schema = opts[:schema] || default_schema
574:           ds.filter(:pg_namespace__nspname=>schema.to_s)
575:         else
576:           ds.exclude(:pg_namespace__nspname=>EXCLUDE_SCHEMAS)
577:         end
578:       end
identifier_input_method_default() click to toggle source

PostgreSQL folds unquoted identifiers to lowercase, so it shouldn’t need to upcase identifiers on input.

     # File lib/sequel/adapters/shared/postgres.rb, line 581
581:       def identifier_input_method_default
582:         nil
583:       end
identifier_output_method_default() click to toggle source

PostgreSQL folds unquoted identifiers to lowercase, so it shouldn’t need to upcase identifiers on output.

     # File lib/sequel/adapters/shared/postgres.rb, line 586
586:       def identifier_output_method_default
587:         nil
588:       end
index_definition_sql(table_name, index) click to toggle source

PostgreSQL specific index SQL.

     # File lib/sequel/adapters/shared/postgres.rb, line 591
591:       def index_definition_sql(table_name, index)
592:         cols = index[:columns]
593:         index_name = index[:name] || default_index_name(table_name, cols)
594:         expr = if o = index[:opclass]
595:           "(#{Array(cols).map{|c| "#{literal(c)} #{o}"}.join(', ')})"
596:         else
597:           literal(Array(cols))
598:         end
599:         unique = "UNIQUE " if index[:unique]
600:         index_type = index[:type]
601:         filter = index[:where] || index[:filter]
602:         filter = " WHERE #{filter_expr(filter)}" if filter
603:         case index_type
604:         when :full_text
605:           expr = "(to_tsvector(#{literal(index[:language] || 'simple')}::regconfig, #{literal(dataset.send(:full_text_string_join, cols))}))"
606:           index_type = :gin
607:         when :spatial
608:           index_type = :gist
609:         end
610:         "CREATE #{unique}INDEX#{' CONCURRENTLY' if index[:concurrently]} #{quote_identifier(index_name)} ON #{quote_schema_table(table_name)} #{"USING #{index_type} " if index_type}#{expr}#{filter}"
611:       end
pg_class_relname(type, opts) click to toggle source

Backbone of the tables and views support.

     # File lib/sequel/adapters/shared/postgres.rb, line 614
614:       def pg_class_relname(type, opts)
615:         ds = metadata_dataset.from(:pg_class).filter(:relkind=>type).select(:relname).exclude(SQL::StringExpression.like(:relname, SYSTEM_TABLE_REGEXP)).server(opts[:server]).join(:pg_namespace, :oid=>:relnamespace)
616:         ds = filter_schema(ds, opts)
617:         m = output_identifier_meth
618:         block_given? ? yield(ds) : ds.map{|r| m.call(r[:relname])}
619:       end
prepared_arg_placeholder() click to toggle source

Use a dollar sign instead of question mark for the argument placeholder.

     # File lib/sequel/adapters/shared/postgres.rb, line 623
623:       def prepared_arg_placeholder
624:         PREPARED_ARG_PLACEHOLDER
625:       end
remove_cached_schema(table) click to toggle source

Remove the cached entries for primary keys and sequences when a table is changed.

     # File lib/sequel/adapters/shared/postgres.rb, line 629
629:       def remove_cached_schema(table)
630:         tab = quote_schema_table(table)
631:         @primary_keys.delete(tab)
632:         @primary_key_sequences.delete(tab)
633:         super
634:       end
rename_table_sql(name, new_name) click to toggle source

SQL DDL statement for renaming a table. PostgreSQL doesn’t allow you to change a table’s schema in a rename table operation, so speciying a new schema in new_name will not have an effect.

     # File lib/sequel/adapters/shared/postgres.rb, line 638
638:       def rename_table_sql(name, new_name)
639:         "ALTER TABLE #{quote_schema_table(name)} RENAME TO #{quote_identifier(schema_and_table(new_name).last)}"
640:       end
schema_autoincrementing_primary_key?(schema) click to toggle source

PostgreSQL’s autoincrementing primary keys are of type integer or bigint using a nextval function call as a default.

     # File lib/sequel/adapters/shared/postgres.rb, line 644
644:       def schema_autoincrementing_primary_key?(schema)
645:         super and schema[:db_type] =~ /\A(?:integer|bigint)\z/o and schema[:default]=~/\Anextval/o
646:       end
schema_parse_table(table_name, opts) click to toggle source

The dataset used for parsing table schemas, using the pg_* system catalogs.

     # File lib/sequel/adapters/shared/postgres.rb, line 649
649:       def schema_parse_table(table_name, opts)
650:         m = output_identifier_meth(opts[:dataset])
651:         m2 = input_identifier_meth(opts[:dataset])
652:         ds = metadata_dataset.select(:pg_attribute__attname___name,
653:             SQL::Function.new(:format_type, :pg_type__oid, :pg_attribute__atttypmod).as(:db_type),
654:             SQL::Function.new(:pg_get_expr, :pg_attrdef__adbin, :pg_class__oid).as(:default),
655:             SQL::BooleanExpression.new(:NOT, :pg_attribute__attnotnull).as(:allow_null),
656:             SQL::Function.new(:COALESCE, SQL::BooleanExpression.from_value_pairs(:pg_attribute__attnum => SQL::Function.new(:ANY, :pg_index__indkey)), false).as(:primary_key),
657:             :pg_namespace__nspname).
658:           from(:pg_class).
659:           join(:pg_attribute, :attrelid=>:oid).
660:           join(:pg_type, :oid=>:atttypid).
661:           join(:pg_namespace, :oid=>:pg_class__relnamespace).
662:           left_outer_join(:pg_attrdef, :adrelid=>:pg_class__oid, :adnum=>:pg_attribute__attnum).
663:           left_outer_join(:pg_index, :indrelid=>:pg_class__oid, :indisprimary=>true).
664:           filter(:pg_attribute__attisdropped=>false).
665:           filter{|o| o.pg_attribute__attnum > 0}.
666:           filter(:pg_class__relname=>m2.call(table_name)).
667:           order(:pg_attribute__attnum)
668:         ds = filter_schema(ds, opts)
669:         current_schema = nil
670:         ds.map do |row|
671:           sch = row.delete(:nspname)
672:           if current_schema
673:             if sch != current_schema
674:               raise Error, "columns from tables in two separate schema were returned (please specify a schema): #{current_schema.inspect}, #{sch.inspect}"
675:             end
676:           else
677:             current_schema = sch
678:           end
679:           row[:default] = nil if blank_object?(row[:default])
680:           row[:type] = schema_column_type(row[:db_type])
681:           [m.call(row.delete(:name)), row]
682:         end
683:       end
set_transaction_isolation(conn, opts) click to toggle source

Set the transaction isolation level on the given connection

     # File lib/sequel/adapters/shared/postgres.rb, line 686
686:       def set_transaction_isolation(conn, opts)
687:         level = opts.fetch(:isolation, transaction_isolation_level)
688:         read_only = opts[:read_only]
689:         deferrable = opts[:deferrable]
690:         if level || !read_only.nil? || !deferrable.nil?
691:           sql = "SET TRANSACTION"
692:           sql << " ISOLATION LEVEL #{Sequel::Database::TRANSACTION_ISOLATION_LEVELS[level]}" if level
693:           sql << " READ #{read_only ? 'ONLY' : 'WRITE'}" unless read_only.nil?
694:           sql << " #{'NOT ' unless deferrable}DEFERRABLE" unless deferrable.nil?
695:           log_connection_execute(conn, sql)
696:         end
697:       end
sql_function_args(args) click to toggle source

Turns an array of argument specifiers into an SQL fragment used for function arguments. See create_function_sql.

     # File lib/sequel/adapters/shared/postgres.rb, line 700
700:       def sql_function_args(args)
701:         "(#{Array(args).map{|a| Array(a).reverse.join(' ')}.join(', ')})"
702:       end
type_literal_generic_bignum(column) click to toggle source

Handle bigserial type if :serial option is present

     # File lib/sequel/adapters/shared/postgres.rb, line 705
705:       def type_literal_generic_bignum(column)
706:         column[:serial] ? :bigserial : super
707:       end
type_literal_generic_file(column) click to toggle source

PostgreSQL uses the bytea data type for blobs

     # File lib/sequel/adapters/shared/postgres.rb, line 710
710:       def type_literal_generic_file(column)
711:         :bytea
712:       end
type_literal_generic_integer(column) click to toggle source

Handle serial type if :serial option is present

     # File lib/sequel/adapters/shared/postgres.rb, line 715
715:       def type_literal_generic_integer(column)
716:         column[:serial] ? :serial : super
717:       end
type_literal_generic_string(column) click to toggle source

PostgreSQL prefers the text datatype. If a fixed size is requested, the char type is used. If the text type is specifically disallowed or there is a size specified, use the varchar type. Otherwise use the type type.

     # File lib/sequel/adapters/shared/postgres.rb, line 723
723:       def type_literal_generic_string(column)
724:         if column[:fixed]
725:           "char(#{column[:size]||255})"
726:         elsif column[:text] == false or column[:size]
727:           "varchar(#{column[:size]||255})"
728:         else
729:           :text
730:         end
731:       end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.