Module: ArJdbc::PostgreSQL

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

Defined Under Namespace

Modules: Column

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



185
186
187
# File 'lib/arjdbc/postgresql/adapter.rb', line 185

def self.arel2_visitors(config)
  {}.tap {|v| %w(postgresql pg jdbcpostgresql).each {|a| v[a] = ::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



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

def self.extended(mod)
  (class << mod; self; end).class_eval do
    alias_chained_method :columns, :query_cache, :pg_columns
  end
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:



181
182
183
# File 'lib/arjdbc/postgresql/adapter.rb', line 181

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.



594
595
596
597
598
599
600
601
602
603
# File 'lib/arjdbc/postgresql/adapter.rb', line 594

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.



509
510
511
512
513
514
515
516
517
# File 'lib/arjdbc/postgresql/adapter.rb', line 509

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



454
455
456
# File 'lib/arjdbc/postgresql/adapter.rb', line 454

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.



606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
# File 'lib/arjdbc/postgresql/adapter.rb', line 606

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.



632
633
634
# File 'lib/arjdbc/postgresql/adapter.rb', line 632

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



636
637
638
639
640
641
# File 'lib/arjdbc/postgresql/adapter.rb', line 636

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

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



438
439
440
# File 'lib/arjdbc/postgresql/adapter.rb', line 438

def create_database(name, options = {})
  execute "CREATE DATABASE \"#{name}\" ENCODING='#{options[:encoding] || 'utf8'}'"
end

#create_savepointObject



242
243
244
# File 'lib/arjdbc/postgresql/adapter.rb', line 242

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

#create_schema(schema_name, pg_username) ⇒ Object



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

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

#current_databaseObject

current database name



360
361
362
363
# File 'lib/arjdbc/postgresql/adapter.rb', line 360

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

#default_sequence_name(table_name, pk = nil) ⇒ Object



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

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_integrity(&block) ⇒ Object

:nodoc:



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

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

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


492
493
494
495
496
497
498
499
500
501
502
503
# File 'lib/arjdbc/postgresql/adapter.rb', line 492

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



442
443
444
# File 'lib/arjdbc/postgresql/adapter.rb', line 442

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

#drop_schema(schema_name) ⇒ Object



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

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

#encodingObject

current database encoding



366
367
368
369
370
371
372
# File 'lib/arjdbc/postgresql/adapter.rb', line 366

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(s) ⇒ Object



550
551
552
553
554
555
556
# File 'lib/arjdbc/postgresql/adapter.rb', line 550

def escape_bytea(s)
  if s
    result = ''
    s.each_byte { |c| result << sprintf('\\\\%03o', c) }
    result
  end
end

#extract_schema_and_table(name) ⇒ Object

Extracts the table and schema name from name



692
693
694
695
696
697
698
699
700
701
702
703
704
705
# File 'lib/arjdbc/postgresql/adapter.rb', line 692

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



651
652
653
# File 'lib/arjdbc/postgresql/adapter.rb', line 651

def index_name_length
  63
end

#indexes(table_name, name = nil) ⇒ Object

Based on postgresql_adapter.rb



385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# File 'lib/arjdbc/postgresql/adapter.rb', line 385

def indexes(table_name, name = nil)
  schema_search_path = @config[:schema_search_path] || select_rows('SHOW search_path')[0][0]
  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 IN (#{schemas}) )
       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

#last_insert_id(table, sequence_name) ⇒ Object



429
430
431
# File 'lib/arjdbc/postgresql/adapter.rb', line 429

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



425
426
427
# File 'lib/arjdbc/postgresql/adapter.rb', line 425

def last_inserted_id(result)
  Hash[Array(*result)].fetch("id") { result }
end

#multi_column_index_limitObject

Gets the maximum number columns postgres has, default 32



380
381
382
# File 'lib/arjdbc/postgresql/adapter.rb', line 380

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



375
376
377
# File 'lib/arjdbc/postgresql/adapter.rb', line 375

def multi_column_index_limit=(limit)
  @multi_column_index_limit = limit
end

#native_database_typesObject



201
202
203
# File 'lib/arjdbc/postgresql/adapter.rb', line 201

def native_database_types
  NATIVE_DATABASE_TYPES
end

#pg_columns(table_name, name = nil) ⇒ Object



351
352
353
354
355
356
357
# File 'lib/arjdbc/postgresql/adapter.rb', line 351

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.



286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/arjdbc/postgresql/adapter.rb', line 286

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



189
190
191
192
193
194
195
196
197
198
199
# File 'lib/arjdbc/postgresql/adapter.rb', line 189

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



333
334
335
336
# File 'lib/arjdbc/postgresql/adapter.rb', line 333

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.



522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
# File 'lib/arjdbc/postgresql/adapter.rb', line 522

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 "'#{escape_bytea(value)}'"
    when 'xml'   then "xml '#{quote_string(value)}'"
    when /^bit/
      case value
      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



569
570
571
# File 'lib/arjdbc/postgresql/adapter.rb', line 569

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

#quote_table_name(name) ⇒ Object



558
559
560
561
562
563
564
565
566
567
# File 'lib/arjdbc/postgresql/adapter.rb', line 558

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:



573
574
575
576
577
578
579
# File 'lib/arjdbc/postgresql/adapter.rb', line 573

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) ⇒ Object



433
434
435
436
# File 'lib/arjdbc/postgresql/adapter.rb', line 433

def recreate_database(name)
  drop_database(name)
  create_database(name)
end

#release_savepointObject



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

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

#remove_index!(table_name, index_name) ⇒ Object

:nodoc:



647
648
649
# File 'lib/arjdbc/postgresql/adapter.rb', line 647

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:



643
644
645
# File 'lib/arjdbc/postgresql/adapter.rb', line 643

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



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

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 sequence to the max value of the table’s pk if present.



266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/arjdbc/postgresql/adapter.rb', line 266

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



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

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

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



340
341
342
343
344
345
346
347
348
349
# File 'lib/arjdbc/postgresql/adapter.rb', line 340

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

#structure_dumpObject



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

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 = @config[:schema_search_path]
  search_path = "--schema=#{search_path}" if 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_count_distinct?Boolean

:nodoc:

Returns:

  • (Boolean)


238
239
240
# File 'lib/arjdbc/postgresql/adapter.rb', line 238

def supports_count_distinct? #:nodoc:
  false
end

#supports_ddl_transactions?Boolean

Returns:

  • (Boolean)


230
231
232
# File 'lib/arjdbc/postgresql/adapter.rb', line 230

def supports_ddl_transactions?
  true
end

#supports_insert_with_returning?Boolean

Returns:

  • (Boolean)


226
227
228
# File 'lib/arjdbc/postgresql/adapter.rb', line 226

def supports_insert_with_returning?
  postgresql_version >= 80200
end

#supports_migrations?Boolean

Does PostgreSQL support migrations?

Returns:

  • (Boolean)


206
207
208
# File 'lib/arjdbc/postgresql/adapter.rb', line 206

def supports_migrations?
  true
end

#supports_savepoints?Boolean

Returns:

  • (Boolean)


234
235
236
# File 'lib/arjdbc/postgresql/adapter.rb', line 234

def supports_savepoints?
  true
end

#supports_standard_conforming_strings?Boolean

Does PostgreSQL support standard conforming strings?

Returns:

  • (Boolean)


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

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 = select('SHOW standard_conforming_strings').to_a[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.



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

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)


676
677
678
679
680
681
682
683
684
685
686
687
688
689
# File 'lib/arjdbc/postgresql/adapter.rb', line 676

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



668
669
670
671
672
673
674
# File 'lib/arjdbc/postgresql/adapter.rb', line 668

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.



656
657
658
659
660
661
662
663
664
665
666
# File 'lib/arjdbc/postgresql/adapter.rb', line 656

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

  case limit
  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
end