Module: ArJdbc::PostgreSQL

Included in:
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
Defined in:
lib/arjdbc/postgresql/adapter.rb,
lib/arjdbc/postgresql/explain_support.rb

Defined Under Namespace

Modules: Column, ExplainSupport

Constant Summary collapse

ADAPTER_NAME =

constants taken from postgresql_adapter in rails project

'PostgreSQL'
NATIVE_DATABASE_TYPES =
{
  :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" },
  :xml         => { :name => "xml" },
  :tsvector    => { :name => "tsvector" }
}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.arel2_visitors(config) ⇒ Object



172
173
174
175
176
177
178
# File 'lib/arjdbc/postgresql/adapter.rb', line 172

def self.arel2_visitors(config)
  {
    'postgresql' => ::Arel::Visitors::PostgreSQL,
    'jdbcpostgresql' => ::Arel::Visitors::PostgreSQL,
    'pg' => ::Arel::Visitors::PostgreSQL
  }
end

.column_selectorObject



13
14
15
# File 'lib/arjdbc/postgresql/adapter.rb', line 13

def self.column_selector
  [/postgre/i, lambda {|cfg,col| col.extend(::ArJdbc::PostgreSQL::Column)}]
end

.extended(mod) ⇒ Object



5
6
7
8
9
10
11
# File 'lib/arjdbc/postgresql/adapter.rb', line 5

def self.extended(mod)
  (class << mod; self; end).class_eval do
    alias_chained_method :columns, :query_cache, :pg_columns
  end

  mod.configure_connection
end

.jdbc_connection_classObject



17
18
19
# File 'lib/arjdbc/postgresql/adapter.rb', line 17

def self.jdbc_connection_class
  ::ActiveRecord::ConnectionAdapters::PostgresJdbcConnection
end

Instance Method Details

#adapter_nameObject

:nodoc:



168
169
170
# File 'lib/arjdbc/postgresql/adapter.rb', line 168

def adapter_name #:nodoc:
  ADAPTER_NAME
end

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

Adds a new column to the named table. See TableDefinition#column for details of the options you can use.



740
741
742
743
744
745
746
747
748
749
# File 'lib/arjdbc/postgresql/adapter.rb', line 740

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

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

  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

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.



630
631
632
633
634
635
636
637
638
# File 'lib/arjdbc/postgresql/adapter.rb', line 630

def add_order_by_for_association_limiting!(sql, options)
  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

#all_schemasObject



544
545
546
# File 'lib/arjdbc/postgresql/adapter.rb', line 544

def all_schemas
  select('select nspname from pg_namespace').map {|r| r["nspname"] }
end

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

Changes the column of a table.



752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
# File 'lib/arjdbc/postgresql/adapter.rb', line 752

def change_column(table_name, column_name, type, options = {})
  quoted_table_name = quote_table_name(table_name)

  begin
    execute "ALTER TABLE #{quoted_table_name} ALTER COLUMN #{quote_column_name(column_name)} TYPE #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
  rescue ActiveRecord::StatementInvalid => e
    raise e if postgresql_version > 80000
    # This is PostgreSQL 7.x, so we have to use a more arcane way of doing it.
    begin
      begin_db_transaction
      tmp_column_name = "#{column_name}_ar_tmp"
      add_column(table_name, tmp_column_name, type, options)
      execute "UPDATE #{quoted_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
    rescue
      rollback_db_transaction
    end
  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.



778
779
780
# File 'lib/arjdbc/postgresql/adapter.rb', line 778

def change_column_default(table_name, column_name, default)
  execute "ALTER TABLE #{quote_table_name(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



782
783
784
785
786
787
# File 'lib/arjdbc/postgresql/adapter.rb', line 782

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

#client_min_messagesObject

Returns the current client message level.



598
599
600
# File 'lib/arjdbc/postgresql/adapter.rb', line 598

def client_min_messages
  exec_query('SHOW client_min_messages', 'SCHEMA')[0]['client_min_messages']
end

#client_min_messages=(level) ⇒ Object

Set the client message level.



603
604
605
# File 'lib/arjdbc/postgresql/adapter.rb', line 603

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

#configure_connectionObject



21
22
23
# File 'lib/arjdbc/postgresql/adapter.rb', line 21

def configure_connection
  self.standard_conforming_strings = true
end

#create_database(name, options = {}) ⇒ Object



512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
# File 'lib/arjdbc/postgresql/adapter.rb', line 512

def create_database(name, options = {})
  options = options.with_indifferent_access
  create_query = "CREATE DATABASE \"#{name}\" ENCODING='#{options[:encoding] || 'utf8'}'"
  create_query += options.symbolize_keys.sum('') do |key, value|
    case key
      when :owner
        " OWNER = \"#{value}\""
      when :template
        " TEMPLATE = \"#{value}\""
      when :tablespace
        " TABLESPACE = \"#{value}\""
      when :connection_limit
        " CONNECTION LIMIT = #{value}"
      else
        ""
    end
  end
  execute create_query
end

#create_savepointObject



280
281
282
# File 'lib/arjdbc/postgresql/adapter.rb', line 280

def create_savepoint
  execute("SAVEPOINT #{current_savepoint_name}")
end

#create_schema(schema_name, pg_username) ⇒ Object



536
537
538
# File 'lib/arjdbc/postgresql/adapter.rb', line 536

def create_schema(schema_name, pg_username)
  execute("CREATE SCHEMA \"#{schema_name}\" AUTHORIZATION \"#{pg_username}\"")
end

#current_databaseObject

current database name



431
432
433
434
# File 'lib/arjdbc/postgresql/adapter.rb', line 431

def current_database
  exec_query("select current_database() as database").
    first["database"]
end

#current_schemaObject

Returns the current schema name.



593
594
595
# File 'lib/arjdbc/postgresql/adapter.rb', line 593

def current_schema
  exec_query('SELECT current_schema', 'SCHEMA')[0]["current_schema"]
end

#default_sequence_name(table_name, pk = nil) ⇒ Object



298
299
300
301
# File 'lib/arjdbc/postgresql/adapter.rb', line 298

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

#disable_referential_integrityObject

:nodoc:



722
723
724
725
726
727
# File 'lib/arjdbc/postgresql/adapter.rb', line 722

def disable_referential_integrity # :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

#distinct(columns, orders) ⇒ Object

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")


613
614
615
616
617
618
619
620
621
622
623
624
# File 'lib/arjdbc/postgresql/adapter.rb', line 613

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

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

  "DISTINCT #{columns}, #{order_columns * ', '}"
end

#drop_database(name) ⇒ Object



532
533
534
# File 'lib/arjdbc/postgresql/adapter.rb', line 532

def drop_database(name)
  execute "DROP DATABASE IF EXISTS \"#{name}\""
end

#drop_schema(schema_name) ⇒ Object



540
541
542
# File 'lib/arjdbc/postgresql/adapter.rb', line 540

def drop_schema(schema_name)
  execute("DROP SCHEMA \"#{schema_name}\"")
end

#encodingObject

current database encoding



437
438
439
440
441
442
443
# File 'lib/arjdbc/postgresql/adapter.rb', line 437

def encoding
  exec_query(<<-end_sql).first["encoding"]
    SELECT pg_encoding_to_char(pg_database.encoding) as encoding
    FROM pg_database
    WHERE pg_database.datname LIKE '#{current_database}'
  end_sql
end

#escape_bytea(string) ⇒ Object



687
688
689
690
691
692
693
694
695
696
697
# File 'lib/arjdbc/postgresql/adapter.rb', line 687

def escape_bytea(string)
  if string
    if supports_hex_escaped_bytea?
      "\\\\x#{string.unpack("H*")[0]}"
    else
      result = ''
      string.each_byte { |c| result << sprintf('\\\\%03o', c) }
      result
    end
  end
end

#extract_schema_and_table(name) ⇒ Object

Extracts the table and schema name from name



843
844
845
846
847
848
849
850
851
852
853
854
855
856
# File 'lib/arjdbc/postgresql/adapter.rb', line 843

def extract_schema_and_table(name)
  schema, table = name.split('.', 2)

  unless table # A table was provided without a schema
    table  = schema
    schema = nil
  end

  if name =~ /^"/ # Handle quoted table names
    table  = name
    schema = nil
  end
  [schema, table]
end

#index_name_lengthObject



797
798
799
# File 'lib/arjdbc/postgresql/adapter.rb', line 797

def index_name_length
  63
end

#indexes(table_name, name = nil) ⇒ Object

Based on postgresql_adapter.rb



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
481
482
483
484
485
486
487
488
489
490
491
492
# File 'lib/arjdbc/postgresql/adapter.rb', line 456

def indexes(table_name, name = nil)
  schemas = schema_search_path.split(/,/).map { |p| quote(p) }.join(',')
  result = select_rows(<<-SQL, name)
    SELECT i.relname, d.indisunique, a.attname, a.attnum, d.indkey
      FROM pg_class t, pg_class i, pg_index d, pg_attribute a,
      generate_series(0,#{multi_column_index_limit - 1}) AS s(i)
     WHERE i.relkind = 'i'
       AND d.indexrelid = i.oid
       AND d.indisprimary = 'f'
       AND t.oid = d.indrelid
       AND t.relname = '#{table_name}'
       AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname = ANY (current_schemas(false)) )
       AND a.attrelid = t.oid
       AND d.indkey[s.i]=a.attnum
    ORDER BY i.relname
  SQL

  current_index = nil
  indexes = []

  insertion_order = []
  index_order = nil

  result.each do |row|
    if current_index != row[0]

      (index_order = row[4].split(' ')).each_with_index{ |v, i| index_order[i] = v.to_i }
      indexes << ::ActiveRecord::ConnectionAdapters::IndexDefinition.new(table_name, row[0], row[1] == "t", [])
      current_index = row[0]
    end
    insertion_order = row[3]
    ind = index_order.index(insertion_order)
    indexes.last.columns[ind] = row[2]
  end

  indexes
end

#insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = []) ⇒ Object

Insert logic for pre-AR-3.1 adapters



372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# File 'lib/arjdbc/postgresql/adapter.rb', line 372

def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = [])
  # Extract the table from the insert sql. Yuck.
  table = sql.split(" ", 4)[2].gsub('"', '')

  # Try an insert with 'returning id' if available (PG >= 8.2)
  if supports_insert_with_returning? && id_value.nil?
    pk, sequence_name = *pk_and_sequence_for(table) unless pk
    if pk
      sql = to_sql(sql, binds)
      return select_value("#{sql} RETURNING #{quote_column_name(pk)}")
    end
  end

  # Otherwise, plain insert
  execute(sql, name, binds)

  # Don't need to look up id_value if we already have it.
  # (and can't in case of non-sequence PK)
  unless id_value
    # If neither pk nor sequence name is given, look them up.
    unless pk || sequence_name
      pk, sequence_name = *pk_and_sequence_for(table)
    end

    # If a pk is given, fallback to default sequence name.
    # Don't fetch last insert id for a table without a pk.
    if pk && sequence_name ||= default_sequence_name(table, pk)
      id_value = last_insert_id(table, sequence_name)
    end
  end
  id_value
end

#last_insert_id(table, sequence_name) ⇒ Object



503
504
505
# File 'lib/arjdbc/postgresql/adapter.rb', line 503

def last_insert_id(table, sequence_name)
  Integer(select_value("SELECT currval('#{sequence_name}')"))
end

#last_inserted_id(result) ⇒ Object

take id from result of insert query



495
496
497
498
499
500
501
# File 'lib/arjdbc/postgresql/adapter.rb', line 495

def last_inserted_id(result)
  if result.is_a? Fixnum
    result
  else
    result.first.first[1]
  end
end

#multi_column_index_limitObject

Gets the maximum number columns postgres has, default 32



451
452
453
# File 'lib/arjdbc/postgresql/adapter.rb', line 451

def multi_column_index_limit
  defined?(@multi_column_index_limit) && @multi_column_index_limit || 32
end

#multi_column_index_limit=(limit) ⇒ Object

Sets the maximum number columns postgres has, default 32



446
447
448
# File 'lib/arjdbc/postgresql/adapter.rb', line 446

def multi_column_index_limit=(limit)
  @multi_column_index_limit = limit
end

#native_database_typesObject



209
210
211
# File 'lib/arjdbc/postgresql/adapter.rb', line 209

def native_database_types
  NATIVE_DATABASE_TYPES
end

#pg_columns(table_name, name = nil) ⇒ Object



422
423
424
425
426
427
428
# File 'lib/arjdbc/postgresql/adapter.rb', line 422

def pg_columns(table_name, name=nil)
  column_definitions(table_name).map do |row|
    ::ActiveRecord::ConnectionAdapters::PostgreSQLColumn.new(
      row["column_name"], row["column_default"], row["column_type"],
      row["column_not_null"] == "f")
  end
end

#pk_and_sequence_for(table) ⇒ Object

Find a table’s primary key and sequence.



324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/arjdbc/postgresql/adapter.rb', line 324

def pk_and_sequence_for(table) #:nodoc:
  # First try looking for a sequence with a dependency on the
  # given table's primary key.
  result = select(<<-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      = '#{quote_table_name(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 = select(<<-end_sql, 'PK and custom sequence')[0]
        SELECT attr.attname,
          CASE
            WHEN split_part(def.adsrc, '''', 2) ~ '.' THEN
              substr(split_part(def.adsrc, '''', 2),
                     strpos(split_part(def.adsrc, '''', 2), '.')+1)
            ELSE split_part(def.adsrc, '''', 2)
          END as relname
        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 = '#{quote_table_name(table)}'::regclass
          AND cons.contype = 'p'
          AND def.adsrc ~* 'nextval'
      end_sql
  end

  [result["attname"], result["relname"]]
rescue
  nil
end

#postgresql_versionObject



180
181
182
183
184
185
186
187
188
189
190
# File 'lib/arjdbc/postgresql/adapter.rb', line 180

def postgresql_version
  @postgresql_version ||=
    begin
      value = select_value('SELECT version()')
      if value =~ /PostgreSQL (\d+)\.(\d+)\.(\d+)/
        ($1.to_i * 10000) + ($2.to_i * 100) + $3.to_i
      else
        0
      end
    end
end

#primary_key(table) ⇒ Object



417
418
419
420
# File 'lib/arjdbc/postgresql/adapter.rb', line 417

def primary_key(table)
  pk_and_sequence = pk_and_sequence_for(table)
  pk_and_sequence && pk_and_sequence.first
end

#quote(value, column = nil) ⇒ Object

from postgres_adapter.rb in rails project github.com/rails/rails/blob/3-1-stable/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb#L412 Quotes PostgreSQL-specific data types for SQL input.



643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
# File 'lib/arjdbc/postgresql/adapter.rb', line 643

def quote(value, column = nil) #:nodoc:
  return super unless column

  case value
  when Float
    return super unless value.infinite? && column.type == :datetime
    "'#{value.to_s.downcase}'"
  when Numeric
    return super unless column.sql_type == 'money'
    # Not truly string input, so doesn't require (or allow) escape string syntax.
    "'#{value}'"
  when String
    case column.sql_type
    when 'bytea' then "E'#{escape_bytea(value)}'::bytea" # "'#{escape_bytea(value)}'"
    when 'xml'   then "xml '#{quote_string(value)}'"
    when /^bit/
      case value
      # NOTE: as reported with #60 this is not quite "right" :
      #  "0103" will be treated as hexadecimal string
      #  "0102" will be treated as hexadecimal string
      #  "0101" will be treated as binary string
      #  "0100" will be treated as binary string
      # ... but is kept due Rails compatibility
      when /^[01]*$/      then "B'#{value}'" # Bit-string notation
      when /^[0-9A-F]*$/i then "X'#{value}'" # Hexadecimal notation
      end
    else
      super
    end
  else
    super
  end
end

#quote_column_name(name) ⇒ Object



710
711
712
# File 'lib/arjdbc/postgresql/adapter.rb', line 710

def quote_column_name(name)
  %("#{name.to_s.gsub("\"", "\"\"")}")
end

#quote_string(string) ⇒ Object

Quotes a string, escaping any ‘ (single quote) and \ (backslash) characters.



679
680
681
682
683
684
685
# File 'lib/arjdbc/postgresql/adapter.rb', line 679

def quote_string(string)
  quoted = string.gsub("'", "''")
  unless standard_conforming_strings?
    quoted.gsub!(/\\/, '\&\&')
  end
  quoted
end

#quote_table_name(name) ⇒ Object



699
700
701
702
703
704
705
706
707
708
# File 'lib/arjdbc/postgresql/adapter.rb', line 699

def quote_table_name(name)
  schema, name_part = extract_pg_identifier_from_name(name.to_s)
    
  unless name_part
    quote_column_name(schema)
  else
    table_name, name_part = extract_pg_identifier_from_name(name_part)
    "#{quote_column_name(schema)}.#{quote_column_name(table_name)}"
  end
end

#quoted_date(value) ⇒ Object

:nodoc:



714
715
716
717
718
719
720
# File 'lib/arjdbc/postgresql/adapter.rb', line 714

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

#recreate_database(name, options = {}) ⇒ Object



507
508
509
510
# File 'lib/arjdbc/postgresql/adapter.rb', line 507

def recreate_database(name, options = {})
  drop_database(name)
  create_database(name, options)
end

#release_savepointObject



288
289
290
# File 'lib/arjdbc/postgresql/adapter.rb', line 288

def release_savepoint
  execute("RELEASE SAVEPOINT #{current_savepoint_name}")
end

#remove_index!(table_name, index_name) ⇒ Object

:nodoc:



793
794
795
# File 'lib/arjdbc/postgresql/adapter.rb', line 793

def remove_index!(table_name, index_name) #:nodoc:
  execute "DROP INDEX #{quote_table_name(index_name)}"
end

#rename_column(table_name, column_name, new_column_name) ⇒ Object

:nodoc:



789
790
791
# File 'lib/arjdbc/postgresql/adapter.rb', line 789

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

#rename_table(name, new_name) ⇒ Object



729
730
731
732
733
734
735
736
# File 'lib/arjdbc/postgresql/adapter.rb', line 729

def rename_table(name, new_name)
  execute "ALTER TABLE #{name} RENAME TO #{new_name}"
  pk, seq = pk_and_sequence_for(new_name)
  if seq == "#{name}_#{pk}_seq"
    new_seq = "#{new_name}_#{pk}_seq"
    execute "ALTER TABLE #{quote_table_name(seq)} RENAME TO #{quote_table_name(new_seq)}"
  end
end

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

Resets sequence to the max value of the table’s pk if present.



304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/arjdbc/postgresql/adapter.rb', line 304

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
      quoted_sequence = quote_column_name(sequence)

      select_value <<-end_sql, 'Reset sequence'
          SELECT setval('#{quoted_sequence}', (SELECT COALESCE(MAX(#{quote_column_name pk})+(SELECT increment_by FROM #{quoted_sequence}), (SELECT min_value FROM #{quoted_sequence})) FROM #{quote_table_name(table)}), false)
        end_sql
    else
      @logger.warn "#{table} has primary key #{pk} with no default sequence" if @logger
    end
  end
end

#rollback_to_savepointObject



284
285
286
# File 'lib/arjdbc/postgresql/adapter.rb', line 284

def rollback_to_savepoint
  execute("ROLLBACK TO SAVEPOINT #{current_savepoint_name}")
end

#schema_search_pathObject

Returns the active schema search path.



588
589
590
# File 'lib/arjdbc/postgresql/adapter.rb', line 588

def schema_search_path
  @schema_search_path ||= exec_query('SHOW search_path', 'SCHEMA')[0]['search_path']
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.



580
581
582
583
584
585
# File 'lib/arjdbc/postgresql/adapter.rb', line 580

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

#sql_for_insert(sql, pk, id_value, sequence_name, binds) ⇒ Object

taken from rails postgresql_adapter.rb



406
407
408
409
410
411
412
413
414
415
# File 'lib/arjdbc/postgresql/adapter.rb', line 406

def sql_for_insert(sql, pk, id_value, sequence_name, binds)
  unless pk
    table_ref = extract_table_ref_from_insert_sql(sql)
    pk = primary_key(table_ref) if table_ref
  end

  sql = "#{sql} RETURNING #{quote_column_name(pk)}" if pk

  [sql, binds]
end

#standard_conforming_strings=(enable) ⇒ Object

Enable standard-conforming strings if available.



214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/arjdbc/postgresql/adapter.rb', line 214

def standard_conforming_strings=(enable)
  client_min_messages = self.client_min_messages
  begin
    self.client_min_messages = 'panic'
    value = enable ? "on" : "off"
    execute("SET standard_conforming_strings = #{value}", 'SCHEMA')
    @standard_conforming_strings = ( value == "on" )
  rescue
    @standard_conforming_strings = :unsupported
  ensure
    self.client_min_messages = client_min_messages
  end
end

#standard_conforming_strings?Boolean

:nodoc:

Returns:

  • (Boolean)


228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/arjdbc/postgresql/adapter.rb', line 228

def standard_conforming_strings? # :nodoc:
  if @standard_conforming_strings.nil?
    client_min_messages = self.client_min_messages
    begin
      self.client_min_messages = 'panic'
      value = select_one('SHOW standard_conforming_strings', 'SCHEMA')['standard_conforming_strings']
      @standard_conforming_strings = ( value == "on" )
    rescue
      @standard_conforming_strings = :unsupported
    ensure
      self.client_min_messages = client_min_messages
    end
  end
  @standard_conforming_strings == true # return false if :unsupported
end

#structure_dumpObject



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
# File 'lib/arjdbc/postgresql/adapter.rb', line 548

def structure_dump
  database = @config[:database]
  if database.nil?
    if @config[:url] =~ /\/([^\/]*)$/
      database = $1
    else
      raise "Could not figure out what database this url is for #{@config["url"]}"
    end
  end

  ENV['PGHOST']     = @config[:host] if @config[:host]
  ENV['PGPORT']     = @config[:port].to_s if @config[:port]
  ENV['PGPASSWORD'] = @config[:password].to_s if @config[:password]
  search_path = "--schema=#{@config[:schema_search_path]}" if @config[:schema_search_path]

  @connection.connection.close
  begin
    definition = `pg_dump -i -U "#{@config[:username]}" -s -x -O #{search_path} #{database}`
    raise "Error dumping database" if $?.exitstatus == 1

    # need to patch away any references to SQL_ASCII as it breaks the JDBC driver
    definition.gsub(/SQL_ASCII/, 'UNICODE')
  ensure
    reconnect!
  end
end

#supports_ddl_transactions?Boolean

:nodoc:

Returns:

  • (Boolean)


268
269
270
# File 'lib/arjdbc/postgresql/adapter.rb', line 268

def supports_ddl_transactions? # :nodoc:
  true
end

#supports_hex_escaped_bytea?Boolean

:nodoc:

Returns:

  • (Boolean)


260
261
262
# File 'lib/arjdbc/postgresql/adapter.rb', line 260

def supports_hex_escaped_bytea? # :nodoc:
  postgresql_version >= 90000
end

#supports_index_sort_order?Boolean

:nodoc:

Returns:

  • (Boolean)


272
273
274
# File 'lib/arjdbc/postgresql/adapter.rb', line 272

def supports_index_sort_order? # :nodoc:
  true
end

#supports_insert_with_returning?Boolean

:nodoc:

Returns:

  • (Boolean)


264
265
266
# File 'lib/arjdbc/postgresql/adapter.rb', line 264

def supports_insert_with_returning? # :nodoc:
  postgresql_version >= 80200
end

#supports_migrations?Boolean

Does PostgreSQL support migrations?

Returns:

  • (Boolean)


245
246
247
# File 'lib/arjdbc/postgresql/adapter.rb', line 245

def supports_migrations? # :nodoc:
  true
end

#supports_primary_key?Boolean

Does PostgreSQL support finding primary key on non-Active Record tables?

Returns:

  • (Boolean)


250
251
252
# File 'lib/arjdbc/postgresql/adapter.rb', line 250

def supports_primary_key? # :nodoc:
  true
end

#supports_savepoints?Boolean

:nodoc:

Returns:

  • (Boolean)


276
277
278
# File 'lib/arjdbc/postgresql/adapter.rb', line 276

def supports_savepoints? # :nodoc:
  true
end

#supports_standard_conforming_strings?Boolean

Does PostgreSQL support standard conforming strings?

Returns:

  • (Boolean)


255
256
257
258
# File 'lib/arjdbc/postgresql/adapter.rb', line 255

def supports_standard_conforming_strings? # :nodoc:
  standard_conforming_strings?
  @standard_conforming_strings != :unsupported
end

#table_alias_lengthObject

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



294
295
296
# File 'lib/arjdbc/postgresql/adapter.rb', line 294

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

#table_exists?(name) ⇒ Boolean

Returns:

  • (Boolean)


827
828
829
830
831
832
833
834
835
836
837
838
839
840
# File 'lib/arjdbc/postgresql/adapter.rb', line 827

def table_exists?(name)
  schema, table = extract_schema_and_table(name.to_s)
  return false unless table # Abstract classes is having nil table name

  binds = [[nil, table.gsub(/(^"|"$)/,'')]]
  binds << [nil, schema] if schema

  exec_query(<<-SQL, 'SCHEMA', binds).first["table_count"] > 0
      SELECT COUNT(*) as table_count
      FROM pg_tables
      WHERE tablename = ?
      AND schemaname = #{schema ? "?" : "ANY (current_schemas(false))"}
  SQL
end

#tables(name = nil) ⇒ Object



819
820
821
822
823
824
825
# File 'lib/arjdbc/postgresql/adapter.rb', line 819

def tables(name = nil)
  exec_query(<<-SQL, 'SCHEMA').map { |row| row["tablename"] }
      SELECT tablename
      FROM pg_tables
      WHERE schemaname = ANY (current_schemas(false))
  SQL
end

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

Maps logical Rails types to PostgreSQL-specific data types.



802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
# File 'lib/arjdbc/postgresql/adapter.rb', line 802

def type_to_sql(type, limit = nil, precision = nil, scale = nil)
  case type.to_sym
  when :integer
    return 'integer' unless limit
    case limit.to_i
      when 1, 2; 'smallint'
      when 3, 4; 'integer'
      when 5..8; 'bigint'
      else raise(ActiveRecordError, "No integer type has byte size #{limit}. Use a numeric with precision 0 instead.")
    end
  when :binary
    super(type, nil, nil, nil)
  else
    super
  end
end