Class: ActiveRecord::ConnectionAdapters::PostgreSQLAdapter

Inherits:
AbstractAdapter
  • Object
show all
Defined in:
lib/active_record/connection_adapters/postgresql_adapter.rb

Overview

The PostgreSQL adapter works both with the native C (ruby.scripting.ca/postgres/) and the pure Ruby (available both as gem and from rubyforge.org/frs/?group_id=234&release_id=1944) drivers.

Options:

  • :host – Defaults to localhost

  • :port – Defaults to 5432

  • :username – Defaults to nothing

  • :password – Defaults to nothing

  • :database – The name of the database. No default, must be provided.

  • :schema_search_path – An optional schema search path for the connection given as a string of comma-separated schema names. This is backward-compatible with the :schema_order option.

  • :encoding – An optional client encoding that is used in a SET client_encoding TO <encoding> call on the connection.

  • :min_messages – An optional client min messages that is used in a SET client_min_messages TO <min_messages> call on the connection.

  • :allow_concurrency – If true, use async query methods so Ruby threads don’t deadlock; otherwise, use blocking query methods.

Instance Method Summary collapse

Methods inherited from AbstractAdapter

#log_info, #prefetch_primary_key?, #quote_table_name, #raw_connection, #requires_reloading?, #reset_runtime, #supports_count_distinct?, #verify!

Methods included from QueryCache

#cache, #uncached

Methods included from Quoting

#quote_table_name, #quoted_false, #quoted_string_prefix, #quoted_true

Methods included from DatabaseStatements

#add_limit!, #add_limit_offset!, #add_lock!, #delete, #empty_insert_statement, #insert_fixture, #reset_sequence!, #select_all, #select_one, #select_value, #select_values, #transaction, #update

Methods included from SchemaStatements

#add_column_options!, #add_index, #create_table, #drop_table, #dump_schema_information, #index_name, #initialize_schema_information, #remove_column, #structure_dump, #table_alias_for

Constructor Details

#initialize(connection, logger, connection_parameters, config) ⇒ PostgreSQLAdapter

Initializes and connects a PostgreSQL adapter.



233
234
235
236
237
238
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 233

def initialize(connection, logger, connection_parameters, config)
  super(connection, logger)
  @connection_parameters, @config = connection_parameters, config

  connect
end

Instance Method Details

#active?Boolean

Is this connection alive and ready for queries?

Returns:

  • (Boolean)


241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 241

def active?
  if @connection.respond_to?(:status)
    @connection.status == PGconn::CONNECTION_OK
  else
    # We're asking the driver, not ActiveRecord, so use @connection.query instead of #query
    @connection.query 'SELECT 1'
    true
  end
# postgres-pr raises a NoMethodError when querying if no connection is available.
rescue PGError, NoMethodError
  false
end

#adapter_nameObject

Returns ‘PostgreSQL’ as adapter name for identification purposes.



228
229
230
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 228

def adapter_name
  'PostgreSQL'
end

#add_column(table_name, column_name, type, options = {}) ⇒ Object

Adds a column to a table.



589
590
591
592
593
594
595
596
597
598
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 589

def add_column(table_name, column_name, type, options = {})
  default = options[:default]
  notnull = options[:null] == false

  # Add the column.
  execute("ALTER TABLE #{table_name} ADD COLUMN #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit])}")

  change_column_default(table_name, column_name, default) if options_include_default?(options)
  change_column_null(table_name, column_name, false, default) if notnull
end

#add_order_by_for_association_limiting!(sql, options) ⇒ Object

Returns an ORDER BY clause for the passed order option.

PostgreSQL does not allow arbitrary ordering when using DISTINCT ON, so we work around this by wrapping the sql as a sub-select and ordering in that query.



679
680
681
682
683
684
685
686
687
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 679

def add_order_by_for_association_limiting!(sql, options) #:nodoc:
  return sql if options[:order].blank?
  
  order = options[:order].split(',').collect { |s| s.strip }.reject(&:blank?)
  order.map! { |s| 'DESC' if s =~ /\bdesc$/i }
  order = order.zip((0...order.size).to_a).map { |s,i| "id_list.alias_#{i} #{s}" }.join(', ')
  
  sql.replace "SELECT * FROM (#{sql}) AS id_list ORDER BY #{order}"
end

#begin_db_transactionObject

Begins a transaction.



422
423
424
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 422

def begin_db_transaction
  execute "BEGIN"
end

#change_column(table_name, column_name, type, options = {}) ⇒ Object

Changes the column of a table.



601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 601

def change_column(table_name, column_name, type, options = {})
  begin
    execute "ALTER TABLE #{table_name} ALTER COLUMN #{quote_column_name(column_name)} TYPE #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
  rescue ActiveRecord::StatementInvalid
    # This is PostgreSQL 7.x, so we have to use a more arcane way of doing it.
    begin_db_transaction
    tmp_column_name = "#{column_name}_ar_tmp"
    add_column(table_name, tmp_column_name, type, options)
    execute "UPDATE #{table_name} SET #{quote_column_name(tmp_column_name)} = CAST(#{quote_column_name(column_name)} AS #{type_to_sql(type, options[:limit], options[:precision], options[:scale])})"
    remove_column(table_name, column_name)
    rename_column(table_name, tmp_column_name, column_name)
    commit_db_transaction
  end

  change_column_default(table_name, column_name, options[:default]) if options_include_default?(options)
  change_column_null(table_name, column_name, options[:null], options[:default]) if options.key?(:null)
end

#change_column_default(table_name, column_name, default) ⇒ Object

Changes the default value of a table column.



620
621
622
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 620

def change_column_default(table_name, column_name, default)
  execute "ALTER TABLE #{table_name} ALTER COLUMN #{quote_column_name(column_name)} SET DEFAULT #{quote(default)}"
end

#change_column_null(table_name, column_name, null, default = nil) ⇒ Object



624
625
626
627
628
629
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 624

def change_column_null(table_name, column_name, null, default = nil)
  unless null || default.nil?
    execute("UPDATE #{table_name} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL")
  end
  execute("ALTER TABLE #{table_name} ALTER #{quote_column_name(column_name)} #{null ? 'DROP' : 'SET'} NOT NULL")
end

#client_min_messagesObject

Returns the current client message level.



508
509
510
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 508

def client_min_messages
  query('SHOW client_min_messages')[0][0]
end

#client_min_messages=(level) ⇒ Object

Set the client message level.



513
514
515
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 513

def client_min_messages=(level)
  execute("SET client_min_messages TO '#{level}'")
end

#columns(table_name, name = nil) ⇒ Object

Returns the list of all column definitions for a table.



483
484
485
486
487
488
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 483

def columns(table_name, name = nil)
  # Limit, precision, and scale are all handled by the superclass.
  column_definitions(table_name).collect do |name, type, default, notnull|
    PostgreSQLColumn.new(name, default, type, notnull == 'f')
  end
end

#commit_db_transactionObject

Commits a transaction.



427
428
429
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 427

def commit_db_transaction
  execute "COMMIT"
end

#default_sequence_name(table_name, pk = nil) ⇒ Object

Returns the sequence name for a table’s primary key or some other specified key.



518
519
520
521
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 518

def default_sequence_name(table_name, pk = nil) #:nodoc:
  default_pk, default_seq = pk_and_sequence_for(table_name)
  default_seq || "#{table_name}_#{pk || default_pk || 'id'}_seq"
end

#disable_referential_integrity(&block) ⇒ Object

REFERENTIAL INTEGRITY ====================================



372
373
374
375
376
377
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 372

def disable_referential_integrity(&block) #:nodoc:
  execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} DISABLE TRIGGER ALL" }.join(";"))
  yield
ensure
  execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} ENABLE TRIGGER ALL" }.join(";"))
end

#disconnect!Object

Close the connection.



266
267
268
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 266

def disconnect!
  @connection.close rescue nil
end

#distinct(columns, order_by) ⇒ Object

Returns a SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.

PostgreSQL requires the ORDER BY columns in the select list for distinct queries, and requires that the ORDER BY include the distinct column.

distinct("posts.id", "posts.created_at desc")


660
661
662
663
664
665
666
667
668
669
670
671
672
673
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 660

def distinct(columns, order_by) #:nodoc:
  return "DISTINCT #{columns}" if order_by.blank?

  # Construct a clean list of column names from the ORDER BY clause, removing
  # any ASC/DESC modifiers
  order_columns = order_by.split(',').collect { |s| s.split.first }
  order_columns.delete_if &:blank?
  order_columns = order_columns.zip((0...order_columns.size).to_a).map { |s,i| "#{s} AS alias_#{i}" }

  # Return a DISTINCT ON() clause that's distinct on the columns we want but includes
  # all the required columns for the ORDER BY to work properly.
  sql = "DISTINCT ON (#{columns}) #{columns}, "
  sql << order_columns * ', '
end

#execute(sql, name = nil) ⇒ Object

Executes an SQL statement, returning a PGresult object on success or raising a PGError exception otherwise.



406
407
408
409
410
411
412
413
414
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 406

def execute(sql, name = nil)
  log(sql, name) do
    if @async
      @connection.async_exec(sql)
    else
      @connection.exec(sql)
    end
  end
end

#indexes(table_name, name = nil) ⇒ Object

Returns the list of all indexes for a table.



449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 449

def indexes(table_name, name = nil)
  result = query(<<-SQL, name)
    SELECT i.relname, d.indisunique, a.attname
      FROM pg_class t, pg_class i, pg_index d, pg_attribute a
     WHERE i.relkind = 'i'
       AND d.indexrelid = i.oid
       AND d.indisprimary = 'f'
       AND t.oid = d.indrelid
       AND t.relname = '#{table_name}'
       AND a.attrelid = t.oid
       AND ( d.indkey[0]=a.attnum OR d.indkey[1]=a.attnum
          OR d.indkey[2]=a.attnum OR d.indkey[3]=a.attnum
          OR d.indkey[4]=a.attnum OR d.indkey[5]=a.attnum
          OR d.indkey[6]=a.attnum OR d.indkey[7]=a.attnum
          OR d.indkey[8]=a.attnum OR d.indkey[9]=a.attnum )
    ORDER BY i.relname
  SQL

  current_index = nil
  indexes = []

  result.each do |row|
    if current_index != row[0]
      indexes << IndexDefinition.new(table_name, row[0], row[1] == "t", [])
      current_index = row[0]
    end

    indexes.last.columns << row[2]
  end

  indexes
end

#insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) ⇒ Object

Executes an INSERT query and returns the new record’s ID



388
389
390
391
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 388

def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
  table = sql.split(" ", 4)[2]
  super || last_insert_id(table, sequence_name || default_sequence_name(table, pk))
end

#native_database_typesObject

:nodoc:



270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 270

def native_database_types #:nodoc:
  {
    :primary_key => "serial primary key",
    :string      => { :name => "character varying", :limit => 255 },
    :text        => { :name => "text" },
    :integer     => { :name => "integer" },
    :float       => { :name => "float" },
    :decimal     => { :name => "decimal" },
    :datetime    => { :name => "timestamp" },
    :timestamp   => { :name => "timestamp" },
    :time        => { :name => "time" },
    :date        => { :name => "date" },
    :binary      => { :name => "bytea" },
    :boolean     => { :name => "boolean" }
  }
end

#pk_and_sequence_for(table) ⇒ Object

Returns a table’s primary key and belonging sequence.



542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 542

def pk_and_sequence_for(table) #:nodoc:
  # First try looking for a sequence with a dependency on the
  # given table's primary key.
  result = query(<<-end_sql, 'PK and serial sequence')[0]
    SELECT attr.attname, seq.relname
    FROM pg_class      seq,
         pg_attribute  attr,
         pg_depend     dep,
         pg_namespace  name,
         pg_constraint cons
    WHERE seq.oid           = dep.objid
      AND seq.relkind       = 'S'
      AND attr.attrelid     = dep.refobjid
      AND attr.attnum       = dep.refobjsubid
      AND attr.attrelid     = cons.conrelid
      AND attr.attnum       = cons.conkey[1]
      AND cons.contype      = 'p'
      AND dep.refobjid      = '#{table}'::regclass
  end_sql

  if result.nil? or result.empty?
    # If that fails, try parsing the primary key's default value.
    # Support the 7.x and 8.0 nextval('foo'::text) as well as
    # the 8.1+ nextval('foo'::regclass).
    result = query(<<-end_sql, 'PK and custom sequence')[0]
      SELECT attr.attname, split_part(def.adsrc, '''', 2)
      FROM pg_class       t
      JOIN pg_attribute   attr ON (t.oid = attrelid)
      JOIN pg_attrdef     def  ON (adrelid = attrelid AND adnum = attnum)
      JOIN pg_constraint  cons ON (conrelid = adrelid AND adnum = conkey[1])
      WHERE t.oid = '#{table}'::regclass
        AND cons.contype = 'p'
        AND def.adsrc ~* 'nextval'
    end_sql
  end
  # [primary_key, sequence]
  [result.first, result.last]
rescue
  nil
end

#query(sql, name = nil) ⇒ Object

Queries the database and returns the results in an Array or nil otherwise.



394
395
396
397
398
399
400
401
402
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 394

def query(sql, name = nil) #:nodoc:
  log(sql, name) do
    if @async
      @connection.async_query(sql)
    else
      @connection.query(sql)
    end
  end
end

#quote(value, column = nil) ⇒ Object

Quotes PostgreSQL-specific data types for SQL input.



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 317

def quote(value, column = nil) #:nodoc:
  if value.kind_of?(String) && column && column.type == :binary
    "#{quoted_string_prefix}'#{column.class.string_to_binary(value)}'"
  elsif value.kind_of?(String) && column && column.sql_type =~ /^xml$/
    "xml '#{quote_string(value)}'"
  elsif value.kind_of?(Numeric) && column && column.sql_type =~ /^money$/
    # Not truly string input, so doesn't require (or allow) escape string syntax.
    "'#{value.to_s}'"
  elsif value.kind_of?(String) && column && column.sql_type =~ /^bit/
    case value
      when /^[01]*$/
        "B'#{value}'" # Bit-string notation
      when /^[0-9A-F]*$/i
        "X'#{value}'" # Hexadecimal notation
    end
  else
    super
  end
end

#quote_column_name(name) ⇒ Object

Quotes column names for use in SQL queries.



356
357
358
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 356

def quote_column_name(name) #:nodoc:
  %("#{name}")
end

#quote_string(s) ⇒ Object

Quotes strings for use in SQL input in the postgres driver for better performance.



338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 338

def quote_string(s) #:nodoc:
  if PGconn.respond_to?(:escape)
    self.class.instance_eval do
      define_method(:quote_string) do |s|
        PGconn.escape(s)
      end
    end
  else
    # There are some incorrectly compiled postgres drivers out there
    # that don't define PGconn.escape.
    self.class.instance_eval do
      undef_method(:quote_string)
    end
  end
  quote_string(s)
end

#quoted_date(value) ⇒ Object

Quote date/time values for use in SQL input. Includes microseconds if the value is a Time responding to usec.



362
363
364
365
366
367
368
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 362

def quoted_date(value) #:nodoc:
  if value.acts_like?(:time) && value.respond_to?(:usec)
    "#{super}.#{sprintf("%06d", value.usec)}"
  else
    super
  end
end

#reconnect!Object

Close then reopen the connection.



255
256
257
258
259
260
261
262
263
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 255

def reconnect!
  if @connection.respond_to?(:reset)
    @connection.reset
    configure_connection
  else
    disconnect!
    connect
  end
end

#remove_index(table_name, options = {}) ⇒ Object

Drops an index from a table.



637
638
639
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 637

def remove_index(table_name, options = {})
  execute "DROP INDEX #{index_name(table_name, options)}"
end

#rename_column(table_name, column_name, new_column_name) ⇒ Object

Renames a column in a table.



632
633
634
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 632

def rename_column(table_name, column_name, new_column_name)
  execute "ALTER TABLE #{table_name} RENAME COLUMN #{quote_column_name(column_name)} TO #{quote_column_name(new_column_name)}"
end

#rename_table(name, new_name) ⇒ Object

Renames a table.



584
585
586
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 584

def rename_table(name, new_name)
  execute "ALTER TABLE #{name} RENAME TO #{new_name}"
end

#reset_pk_sequence!(table, pk = nil, sequence = nil) ⇒ Object

Resets the sequence of a table’s primary key to the maximum value.



524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 524

def reset_pk_sequence!(table, pk = nil, sequence = nil) #:nodoc:
  unless pk and sequence
    default_pk, default_sequence = pk_and_sequence_for(table)
    pk ||= default_pk
    sequence ||= default_sequence
  end
  if pk
    if sequence
      select_value <<-end_sql, 'Reset sequence'
        SELECT setval('#{sequence}', (SELECT COALESCE(MAX(#{pk})+(SELECT increment_by FROM #{sequence}), (SELECT min_value FROM #{sequence})) FROM #{table}), false)
      end_sql
    else
      @logger.warn "#{table} has primary key #{pk} with no default sequence" if @logger
    end
  end
end

#rollback_db_transactionObject

Aborts a transaction.



432
433
434
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 432

def rollback_db_transaction
  execute "ROLLBACK"
end

#schema_search_pathObject

Returns the active schema search path.



503
504
505
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 503

def schema_search_path
  @schema_search_path ||= query('SHOW search_path')[0][0]
end

#schema_search_path=(schema_csv) ⇒ Object

Sets the schema search path to a string of comma-separated schema names. Names beginning with $ have to be quoted (e.g. $user => ‘$user’). See: www.postgresql.org/docs/current/static/ddl-schemas.html

This should be not be called manually but set in database.yml.



495
496
497
498
499
500
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 495

def schema_search_path=(schema_csv)
  if schema_csv
    execute "SET search_path TO #{schema_csv}"
    @schema_search_path = schema_csv
  end
end

#select_rows(sql, name = nil) ⇒ Object

Executes a SELECT query and returns an array of rows. Each row is an array of field values.



383
384
385
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 383

def select_rows(sql, name = nil)
  select_raw(sql, name).last
end

#supports_migrations?Boolean

Does PostgreSQL support migrations?

Returns:

  • (Boolean)


288
289
290
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 288

def supports_migrations?
  true
end

#supports_standard_conforming_strings?Boolean

Does PostgreSQL support standard conforming strings?

Returns:

  • (Boolean)


293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 293

def supports_standard_conforming_strings?
  # Temporarily set the client message level above error to prevent unintentional
  # error messages in the logs when working on a PostgreSQL database server that
  # does not support standard conforming strings.
  client_min_messages_old = client_min_messages
  self.client_min_messages = 'panic'

  # postgres-pr does not raise an exception when client_min_messages is set higher
  # than error and "SHOW standard_conforming_strings" fails, but returns an empty
  # PGresult instead.
  has_support = execute('SHOW standard_conforming_strings')[0][0] rescue false
  self.client_min_messages = client_min_messages_old
  has_support
end

#table_alias_lengthObject

Returns the configured supported identifier length supported by PostgreSQL, or report the default of 63 on PostgreSQL 7.x.



310
311
312
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 310

def table_alias_length
  @table_alias_length ||= (postgresql_version >= 80000 ? query('SHOW max_identifier_length')[0][0].to_i : 63)
end

#tables(name = nil) ⇒ Object

Returns the list of all tables in the schema search path or a specified schema.



439
440
441
442
443
444
445
446
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 439

def tables(name = nil)
  schemas = schema_search_path.split(/,/).map { |p| quote(p) }.join(',')
  query(<<-SQL, name).map { |row| row[0] }
    SELECT tablename
      FROM pg_tables
     WHERE schemaname IN (#{schemas})
  SQL
end

#type_to_sql(type, limit = nil, precision = nil, scale = nil) ⇒ Object

Maps logical Rails types to PostgreSQL-specific data types.



642
643
644
645
646
647
648
649
650
651
652
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 642

def type_to_sql(type, limit = nil, precision = nil, scale = nil)
  return super unless type.to_s == 'integer'

  if limit.nil? || limit == 4
    'integer'
  elsif limit < 4
    'smallint'
  else
    'bigint'
  end
end

#update_sql(sql, name = nil) ⇒ Object

Executes an UPDATE query and returns the number of affected tuples.



417
418
419
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 417

def update_sql(sql, name = nil)
  super.cmdtuples
end